vue3 父子组件共享响应式对象

发布时间 2023-04-15 10:19:44作者: lin_0110

父组件

<template lang="">
  <div>
    <div class="greetings">按钮值:{{ num }}</div>
    <div>
      <button @click="num++">按钮</button>
    </div>

    <div> i am parent</div>
    <button @click="addList">list新增</button>
    <ul>
      <li v-for="item in list">{{item}}</li>
    </ul>
    <Child :list="list"></Child>
  </div>
</template>
<script>
export default {};
</script>
<script setup>
import { ref } from "vue";
import Child from './Child.vue'
const num = ref(0);
const list = ref([
  '标题1', '标题2'
])
let i = 2;
const addList = () => {
  list.value.push('标题' + ++i)
}
</script>
<style lang=""></style>

子组件

<template lang="">
  <div>
    <p>i am child</p>
    <ul>
      <li v-for="item in props.list">{{item}}</li>
    </ul>
    <button @click='deleteOne'>删除list</button>
  </div>
</template>
<script>
export default {};
</script>

<script setup>
const a = 1;
const props = defineProps(['list'])
console.log('获取到的props', props)
console.log('获取到的props.list', props.list)
// console.log(list)
// const list = ref(['2123'])
const deleteOne = () => {
  let list = props.list 
  list.splice(0, 1)
}
</script>
<style lang=""></style>

最终效果

初始

点击父组件新增

点击子组件删除