使用实例作为VueJS数据



首先,很抱歉我的英语不好。

我的问题是:我可以在VueJS中使用实例作为数据吗?

看看这两种更新用户名的方法。

const vue = new Vue({
data(){
return {
user: {
name: 'Denis Wilton',
},
}
},
methods: {
updateUserName(newName) {
this.user.name = newName;
}
}
})
<button @click="updateUserName('Foo Bar')">Change name to Foo Bar</button>

通过上述方式,我可以创建一个调用方法"的事件;updateUserName(‘Foo Bar’(";将newName作为参数传递。

好的!但是如果我从user类创建一个用户实例,它自己携带updateName方法,如下所示:

//@/classes/User.js
//Class User
class User {

constructor(name) {
this.name = name;
}
updateName(newName) {
this.name = newName;
}
}

//////////////////////////////
const vue = new Vue({
data(){
return {
user: new User('Denis Wilton'), //Here I instantiated my user class, that owns the 'updateUser' method implicitly.
}
}
});

在上面的例子中,我可以使用调用User方法"的事件;updateName";用于更新我的数据,并且不需要在VueJS组件的脚本中编写方法。

<button @click="user.updateName('Foo Bar')">Change name to Foo Bar</button>

我做这件事有罪吗?LOL

对此的最佳响应是在reddit线程上:https://www.reddit.com/r/vuejs/comments/gqx58s/anyone_using_oop_principles_in_their_vuejs_spa/

总结:如果你在vue中使用OOP原则,它可能会扰乱vue的内置反应性,并给你带来问题。

最新更新