What's the correct to modify VUE component via

2019-08-01 22:20发布

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 )

标签: vue.js
1条回答
混吃等死
2楼-- · 2019-08-01 22:57

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>

JSFiddle

查看更多
登录 后发表回答