您现在的位置:首页 >> 前端 >> 内容

vue组件通信(父子组件通信)

时间:2018/7/5 16:13:40 点击:

  核心提示:Vue 中主要核心功能有两个,第一:数据绑定系统,第二:组件系统,在组件中经常会遇到子组件触发父组件事件,父组件调用子组件方法,我们称组件通信,组件通信可以分为两种:第一种父子组件通信,第二种非父子组...

Vue 中主要核心功能有两个,第一:数据绑定系统,第二:组件系统,在组件中经常会遇到子组件触发父组件事件,父组件调用子组件方法,我们称组件通信,组件通信可以分为两种:第一种父子组件通信,第二种非父子组件通信,下面文章主要讲解父子组件通信:

一.创建一个父组件Parent.vue添加如下代码


<script>
//一.引用组件
// 一.1:使用 import 引入需要的组件
import Child from "./Child";
export default {
  data() {
    return {
      msg: [1, 2, 3],
      toChild: "我是被引用的子组件",
      ParentData: 1,
      idOne: 1,
      idTwo: 2
    };
  },
  methods: {
    ChengeParent(event) {
      this.ParentData++;
      alert(event);
    }
  },
  //一.2. 注册组件
  components: {
    // 一.2.1: quote-child-components 是在template中使用的名子,不能使用驼峰,html不认识大小写
    // 一.2.2: Child 是 import 组件的名字
    "quote-child-components": Child
  }
};
</script>

二.创建子组件child.vue添加如下代码


<script>
export default {
  data() {
    return {};
  },
  props: {
    toChildData: Array,
    fromMsg: {
      type: String,
      default: ""
    },
    id: Number
  },
  methods: {
    getMsg() {
      //console.log(this.toChildData);
    },
    changeParentMethod() {
      // 三.2:通过 $emit 调用父组件方法
      // 三.3:第一个参数 在父组件 页面应用子组件的地方 定义的 供子组件触发方法的名称 responseChild
      // 三.4:第二参数 带给父组件的数据
      // 三.5:转到父组件
      this.$emit("responseChild", "收到来自子组件的消息");
    }
  },
  created() {
    this.getMsg();
  },
  components: {}
};
</script>

可能 看着会有晕,没关系 点击这里

这是我个人学习Vue时做的练习,将项目下载到本地后 在终端中 执行 npm install 命令,等待项目依赖安装完成后,npm start 启动项目就可以了,页面中有详细的注释说明

注意:在 src/compontents/Parent-childComponentsCommunication中是完整的父子组件通信案例

vue中非父子组件通信


Tags:VU UE E组 组件 
作者:网络 来源:bianliuzhu
  • 上一篇:vue:vuex详解
  • 下一篇:Angular&&Serverless