Vue组件使用、父子组件传值

组件使用

一、创建组件

  三个模板,template、script、style分别对应html、js、css

  template中只能有一个父标签,不能并列多个父标签

  script必须export 一个默认函数,拥有name属性和data方法,data必须有返回值

  style标签最好加入scoped属性,声明样式只对当前组件有效

<template>
    <div class="app">
        <h1>{{msg}}</h1>
    </div>
</template>

<script>
export default {
    name:"App",
    data(){
        return{
            msg:"内容区"
        }
    },
    methods:{

    },
    computed:{

    }
}
</script>

<style scoped>

</style>

二、父组件使用组件

  1、引入

  2、挂载

  3、使用

<template>
  <div class="app">
    <h1>{{msg}}</h1>
    <!-- 使用子组件 -->
    <HelloWorld></HelloWorld>
    <hr>
    <!-- 可以重复使用 -->
    <HelloWorld></HelloWorld>
    <hr>
    <Vcontent></Vcontent>
  </div>
</template>

<script>
//引入子组件
import HelloWorld from "./components/HelloWorld"
import Vcontent from "./components/Vcontent"
export default {
  name : "App",
  data(){
    return {
      msg:"hello"
    }
  },
  methods:{

  },
  computed:{

  },
  //挂载子组件
  components:{
    HelloWorld,  //HelloWorld:HelloWorld
    Vcontent
  }
}
</script>


<style scoped>

</style>

父组件向子组件传值

  1、父组件在使用子组件时绑定属性,值为需要传递的值

// 使用子组件,并传值sites
<Vcontent :siteArray="sites"></Vcontent>
export default {
  name : "App",
  data(){
    return {
      sites:["北京", "上海", "广州"]
    }
  },

  2、子组件props验证属性

export default {
    name:"App",
    data(){
        return{
        }
    },
    //验证属性,传递过来的值是什么类型
    props:{
        siteArray:Array
    }
}

  3、子组件使用

<h1 v-for="items in siteArray">{{items}}</h1>

子组件向父组件传值

  通过触发事件传值,在子组件中使用this.$emit方法

  1、父组件在使用子组件时自定义事件

//自定义downData事件
<Vcontent :siteArray="sites" v-on:downData="parentAddData"></Vcontent>

  2、子组件发动传值请求,使用this.$emit驱动父组件事件

<button v-on:click="addData">向父组件添加值</button>

methods:{
        addData(){
            this.$emit("parentAddData","杭州") //(事件名,值) } },

  3、父组件执行自定义事件

methods:{
      parentAddData(data){
        this.sites.push(data)
      }
  },
原文地址:https://www.cnblogs.com/aizhinong/p/12606427.html