How to update a Vue component props object from outside?
How to update a Vue component props object from outside?
I need to update the props object of a Vue component from outside Vue. I have a solution which seems to work but I get a warning that I want to get rid of.
props
I create a Vue compoent like this:
this.vm = return new Vue({
render: h => h(component, {
props: propsData,
})
}).$mount(el);
Then in a function I update the props from outside Vue as follows
this.updateProps = function (props) {
const children = this.vm.$children;
const firstChild = children && children[0];
if (!firstChild) {
return;
}
_.each(_.keys(firstChild.$props || {}), (key, i) => {
firstChild.$props[key] = props[key];
});
}
This works, but I get the this warning message:
[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: "xxxx"
[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: "xxxx"
How should this be done correctly, without getting a warning?
1 Answer
1
You can't. As in that warning, create your own data in component and use the props as initial value, or use computed property.For example:
props: ['initialCounter'],
data: () => ({
counter: this.initialCounter
})
Or:
props: ['size'],
computed: {
normalizedSize () {
return this.size.trim().toLowerCase()
}
}
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.