通过javascript修改VUE组件的正确方法是什么? [英] What's the correct to modify VUE component via javascript?
问题描述
javascript
(function(exports){Vue.component('我的组件',{道具: {名称:字符串},模板:'\<h1>名称:{{名称}}</h1>\</div>\'});var myApp = new Vue({el: '#myApp'});出口.app = myApp;});html
<我的组件名称=哟!"ref="test"></my-component>
控制台或javascript访问组件
app.$refs.test.name = "yo man";
然后控制台显示Vue警告如下.通过javascript修改VUE组件的正确方法是什么?
[Vue 警告]:避免直接改变 prop,因为每当父组件重新渲染时,该值将被覆盖.相反,根据道具的值使用数据或计算属性.道具正在变异:名称"(在组件中找到)
解决方案 您应该做的是将 name 指令绑定到父应用程序中的变量.
(function(exports){Vue.component('我的组件',{道具: {名称:字符串},模板:'<div><h1>名称:{{name}}</h1></div>'});var myApp = new Vue({el: '#myApp',数据: {姓名:哟!"}});出口.app = myApp;}))();
还有你的 HTML
<my-component v-bind:name="name" ref="test"></my-component><button v-on:click="name = 'Yo man'">更改</button>
javascript
(function(exports){
Vue.component('my-component',{
props: {
name: String
},
template: '<div>\
<h1>name: {{name}}</h1>\
</div>\
'
});
var myApp = new Vue({
el: '#myApp'
});
exports.app = myApp;
});
html
<div id="myApp">
<my-component name="yo!" ref="test"></my-component>
</div>
console or javascript to access component
app.$refs.test.name = "yo man";
Then console display Vue Warning as following.
What's the correct to modify VUE component via javascript?
[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "name"
(found in component )
解决方案 What you should be doing is binding the name directive to a variable in the parent app.
(function(exports){
Vue.component(
'my-component',
{
props: {
name: String
},
template: '<div><h1>name: {{name}}</h1></div>'
}
);
var myApp = new Vue(
{
el: '#myApp',
data: {
name: "Yo!"
}
}
);
exports.app = myApp;
}
))();
And your HTML
<div id="myApp">
<my-component v-bind:name="name" ref="test"></my-component>
<button v-on:click="name = 'Yo man'">Change</button>
</div>
这篇关于通过javascript修改VUE组件的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文