Vue定义了方法,不起作用
vue.js:634 [Vue warn]: Property or method “incr” is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property.
<div id="app">
v-text:<span v-text="hello"></span><br/>
v-html:<span v-html="hello"></span><br/>
<input type="text" v-model="num">
<input type="button" v-on:click="incr" value="点我呀">
<h2>{{name}}, 非常帅!!!有{{num}}个</h2>
</div>
<script src="node_modules/vue/dist/vue.js"></script>
<SCRIPT>
//初始化一个vue实例
let app = new Vue({
el: "#app", //element:选择器
data: { //定义数据模型
name: "Fanor",
num: 50,
hello: "<h1>大家好</h1>",
methods: {
incr() {
this.num += 1;
}
},
created() {
this.num = 2000;
}
}
});
</SCRIPT>
解决
把methods移到data外!!!生命周期函数created和methods是平级!!!
<SCRIPT>
//初始化一个vue实例
let app = new Vue({
el: "#app", //element:选择器
data: { //定义数据模型
name: "Fanor",
num: 50,
hello: "<h1>大家好,我是</h1>",
},
methods: {
incr() {
this.num += 1;
}
},
created() {
this.num = 2000;
}
});
</SCRIPT>
本文探讨了Vue中方法定义的正确方式,指出将方法放置于data外部的重要性,并通过实例展示了如何避免常见的incr方法未定义错误。同时,强调了methods与生命周期函数created的平级关系。

9308

被折叠的 条评论
为什么被折叠?



