美文网首页
vue3.0组件的使用方法和2.0的区别

vue3.0组件的使用方法和2.0的区别

作者: 俗人彭jin | 来源:发表于2020-04-20 01:13 被阅读0次

我们这边在来讨论一下vue3.0组件的使用方法

在开始介绍3.0组件的用法之前,我们可以先回顾一下2.0使用组件的方式。 在2.0当中,哪个页面需要使用组件就在哪个页面里引入该组件,同时在页面注册这个组件。在传递参数时,父组件传递参数给子组件,子组件就会接收父组件传递过来的参数。

举个栗子:

<template>
  <div id="app">
    <HelloWorld msg="Welcome to Your Vue.js App"/>
  </div>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue'

export default {
  name: 'App',
  components: {
    HelloWorld
  }
}
</script>

子组件
<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  data(){
    return{
      
    }
  },
  method:{
    handleClick(){
      this.$emit('childclick','123')
    }
  }
}
</script>

以上是最常见的父子组件之间的调用,但是在vue3.0中就存在差异。

废话不多说,先上DJ(代码)! 先上DJ(代码)!
父组件

<template>
  <div class="hello">
    <div>123</div>
  <NewComp :name="name" @childClick="parentClick"/>
  </div>
  
</template>

<script>
import {reactive} from 'vue'
import NewComp from './newComp.vue'
export default {
  components:{
    NewComp
  },
 setup(){
   const name=reactive({
     name:'hello 番茄'
   })
   const parentClick=(e)=>{
     console.log(e)
     console.log('123')
   }
   return {name,parentClick}
 }  
}
</script>

子组件

<template>
    <div>
        <button @click="handleClick">组件</button>
    </div>
</template>

<script>
export default {
    setup(props,{emit} ){
        const handleClick=()=>{
            emit('childClick','hello')
        }
        return {
            props,
            handleClick
        }
    }
}
</script>

通过上面的vue3.0父子组件之间的调用,我们不难发现,父组件当中在调用子组件时,基本与2.0相同,而在子组件当中,要想获取到父组件传递过来的参数,我们是直接在setup()中直接获取到props值和emit事件。这是因为setup为我们提供了props以及context这两个属性,而在context中又包含了emit等事件。
或许有人看到这里会问,为什么不用this.$emit的方法来向外触发子组件事件呢?

因为在3.0当中已经不在使用this关键词

其他作者目前能感觉到的的变化可以参考上一篇vue2.0与3.0对比以及vue3.0 API变化入门

相关文章

网友评论

      本文标题:vue3.0组件的使用方法和2.0的区别

      本文链接:https://www.haomeiwen.com/subject/uqanbhtx.html