简体   繁体   English

如何在 vue js 中使用 watch 功能

[英]how to use watch function in vue js

could you please tell me how to use watch function in vue js .I tried to used but I got this error.能否请您告诉我如何在 vue js 中使用 watch 功能。我尝试使用但出现此错误。

vue.js:485 [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: "m"

found in

---> <AddTodo>
       <Root>

https://plnkr.co/edit/hVQKk3Wl9DF3aNx0hs88?p=preview https://plnkr.co/edit/hVQKk3Wl9DF3aNx0hs88?p=preview

I created different components and watch properties in the main component我在主组件中创建了不同的组件和监视属性

var AddTODO = Vue.extend({
    template: '#add-todo',
    props: ['m'],
    data: function () {
        return {
            message: ''
        }
    },
    methods: {
        addTodo: function () {
            console.log(this.message)
            console.log(this.m);
            this.m =this.message;
        },
    },
});

When I try to add item I am getting this error.当我尝试添加item时,我收到此错误。 Step to reproduce this bug重现此错误的步骤

  1. Type anything on input field and click on Add button在输入字段中输入任何内容,然后单击Add button
this.m =this.message;

this line is the issue,这条线是问题所在,

It's recommended that you don't modify prop directly...建议不要直接修改prop...

instead create a data property and then modify it.而是创建一个数据属性,然后对其进行修改。

It shows warning because you're modifying the prop item, prop value will be overwritten whenever the parent component re-renders.它显示警告,因为您正在修改道具项目,只要父组件重新渲染,道具值就会被覆盖。

The component's props are automatically updated in the component as soon as you change their value outside of it.只要您在组件之外更改它们的值,组件的 props 就会在组件中自动更新。 For this reason, trying to change the value of a property from inside your component is a bad idea: you should use the props as read-only.出于这个原因,尝试从组件内部更改属性的值是一个坏主意:您应该将 props 用作只读。 If you want to use a prop as the initial value of some of your component's data you can simply declare it this way:如果你想使用一个道具作为你的一些组件data的初始值,你可以简单地这样声明它:

data: function () {
    return {
        changeable: this.receivedProp;
    }
},

That being said, if you are trying to change the value of a prop from inside a component to be able to use your reassigned prop outside of it, you are doing it the wrong way.话虽如此,如果您试图从组件内部更改道具的值,以便能够在组件外部使用重新分配的道具,那么您的做法是错误的。 The way you should handle this is by using Vue's custom events .您应该使用Vue 的自定义事件来处理这个问题。 Remember, as Vue's documentation states:请记住,正如 Vue 的文档所述:

In Vue, the parent-child component relationship can be summarized as props down, events up.在 Vue 中,父子组件关系可以概括为 props down,events up。 The parent passes data down to the child via props, and the child sends messages to the parent via events.父级通过 props 向下传递数据给子级,子级通过事件向父级发送消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM