vue2和vue3混用如何数据共享,vue3中获取vue2数据,vue2获取vue3数据

163 阅读1分钟
<script>
import { getCurrentInstance, ref, onMounted } from 'vue'

export default {
  // -------------vue2-------------
  data() {
    return {
      vue2Title: "this is vue2"
    }
  },
  mounted() {
    // 获取vue3的数据
    console.log(this.vue3Count);
  },
  // -------------vue3-------------
  setup() {
    onMounted(() => {
      const instance = getCurrentInstance()
      // 获取vue2的数据
      const vue2Title = ref(instance.proxy.$data.vue2Title)
      console.log(vue2Title.value);
    })

    const vue3Count = ref(0)
    const addCount = () => {
      vue3Count.value++
    }

    return { count, add}
  }
}
</script>

因为setup本质就是一个Vue实例的生命周期函数,所以Vue 2中直接通过this访问Vue实例即可获取Vue 3定义的数据。而Vue 3获取Vue 2的数据则需要使用getCurrentInstance获取当前组件实例,从而获取Vue 2中的数据。

如果将<script>拆分开的话,Vue 3获取Vue 2的数据还是一样的方法,但是Vue 2获取Vue 3的数据比较麻烦,可能需要定义公共状态实现共享(如store、全局global等),这里就不演示了。

// Vue 3
<script setup>
import { getCurrentInstance, ref, onMounted } from 'vue'

const vue3Count = ref(0)
onMounted(() => {
  const instance = getCurrentInstance()
  // 获取Vue 2的数据
  const vue2Title = ref(instance.proxy.$data.vue2Title)
  console.log("Vue 3", vue2Title.value);
})

</script>

// Vue 2
<script>
export default {
  data() {
    return {
      vue2Title: "this is Vue 2"
    }
  },
}
</script>