js Object reference All In One
js Object reference All In One
bad hacks
<!-- 推荐方式 ✅ 使用 $emit event 修改form -->
<AdAssembleCreative
v-else
@update-form="autoUpdateRuleForm"
:spreaderId="spreaderId"
:ruleForm="ruleForm"
:isUpdate="ruleForm.creativeContent < 1"
:creativeObj="ruleForm.sequencing"
:isEdit="isEdit">
</AdAssembleCreative>
<!-- 不推荐方式 ❌ form.xxx 使用对象引用修改 form -->
<AdAssembleCreative
v-else
:audienceIds="infoObj.package_ids"
:spreaderId="spreaderId"
:ruleForm="ruleForm"
:isUpdate="ruleForm.creativeContent < 1"
:creativeObj="ruleForm.sequencing"
:isEdit="isEdit">
</AdAssembleCreative>
best practice
❌ 提示
注意在 JavaScript 中对象和数组是通过引用传入的,所以对于一个数组或对象类型的 prop 来说,在子组件中改变变更这个对象或数组本身将会影响到父组件的状态。
https://v3.cn.vuejs.org/guide/component-props.html#单向数据流
vue demo
子组件更新父组件的 object
import log from "../utils/log";
import ChildComponent from './child';
const ParentComponent = {
template: `
<div class="parent">
<h2>parent-lifecycle-order</h2>
<button @click="toggleShow">toggleShow</button>
<ChildComponent v-if="show" :obj="obj"/>
<div>{{json}}</div>
</div>
`,
components: {
ChildComponent,
},
data() {
log(`parent init`, 2)
return {
show: true,
obj: {
name: "xgqfrms",
id: 2021,
},
};
},
computed: {
json () {
return JSON.stringify(this.obj, null, 4);
}
},
methods: {
toggleShow() {
const { show } = this;
this.show = !show;
},
},
beforeCreate() {
log(`parent beforeCreate`, 1)
},
created() {
log(`parent created`, 3)
},
beforeMount() {
log(`parent beforeMount`, 4)
},
mounted() {
log(`parent mounted`, 5)
},
beforeUpdate() {
log(`parent beforeUpdate`, 6)
},
updated() {
log(`parent updated`, 7)
},
beforeDestroy() {
log(`\nparent beforeDestroy`, 8)
},
destroyed() {
log(`parent destroyed`, 9)
},
// catch error
};
export {
ParentComponent,
}
export default ParentComponent;
import log from "../utils/log";
const ChildComponent = {
template: `
<div class="child">
<h3>parent-lifecycle-order</h3>
</div>
`,
props: {
obj: {
type: Object,
default: () => ({}),
},
},
data() {
log(`child init`, 2)
return {
//
};
},
beforeCreate() {
log(`child beforeCreate`, 1)
},
created() {
log(`child created`, 3)
},
beforeMount() {
log(`child beforeMount`, 4)
},
mounted() {
log(`child mounted`, 5);
const that = this;
setTimeout(() => {
that.obj.name = "webgeeker";
}, 3000);
},
beforeUpdate() {
log(`child beforeUpdate`, 6)
},
updated() {
log(`child updated`, 7)
},
beforeDestroy() {
log(`\nchild beforeDestroy`, 8)
},
destroyed() {
log(`child destroyed`, 9)
},
// catch error
};
export {
ChildComponent,
}
export default ChildComponent;
refs
©xgqfrms 2012-2020
www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/14483677.html
未经授权禁止转载,违者必究!