正确实例(采用readonly)
作者:互联网
父组件 : <template> <div> 父组件 : {{data.name}} - {{data.age}} - {{data.hight}} <hr> <Hello :data="data" :readonlyData="readonlyData" @readonlyChange="readonlyChange"></Hello> </div> </template> <script> import Hello from './components/Hello.vue' import {reactive, readonly} from 'vue' export default { components:{ Hello }, setup(){ const data = reactive({ name:'吴宇腾', age:39, hight:1.88 }) // 采用readonly const readonlyData = readonly(data) // 自定义事件 const readonlyChange = (name,age)=>{ data.name = name data.age += age } return { data, readonlyData, readonlyChange } } } </script>
子组件 : <template> <div> 子组件 : {{data.name}} - {{data.age}} - {{data.hight}} <br> <button @click="data.name = '杨浩楠' ,data.age++">错误师范,不知道单向数据流,直接修改传递过来的值</button> <hr> 子组件采用readonly : {{readonlyData.name}} - {{readonlyData.age}} - {{readonlyData.hight}} <button @click="readonlyData.name = '杨浩楠' ,readonlyData.age++">采用readonly,想直接修改,不行</button> <button @click="readonlyChange"> 正确修改 : 传递给父组件 </button> </div> </template> <script> export default { name:'Hello', props:['data','readonlyData'], setup(props,context){ // 发送自定义事件 const readonlyChange = ()=>{ context.emit('readonlyChange','杨浩楠ro',1) } return { readonlyChange } } } </script> <style> </style>
标签:readonlyChange,正确,age,readonly,实例,readonlyData,data,name 来源: https://www.cnblogs.com/qd-lbxx/p/16619360.html