当前位置:首页 > vue > 正文内容

vue组件间传值

xi7年前 (2019-11-14)vue1329

父传子

利用props传值,子组件中规定props数据类型,然后父组件使用子组件时需要绑定数据在子组件上:
父组件:

<template>
  <div class="parents-div">
    <!--绑定msg传入子组件-->
    <Children :msg='msg'/>
  </div>
</template>

<script>
import Children from './Children.vue'//引入子组件
export default {
  components:{Children},//注册子组件
  data(){
    return{
      msg:"test",//父组件需要传递的数据
    }
  },
}
</script>
<style scoped>
.parents-div{}
</style>

子组件:

<template>
  <div class="children-div">
    <!--页面中使用数据-->
    {{msg}}
  </div>
</template>

<script>
export default {
  props:{
    msg:String,//子组件需要接受的数据
  },
  components:{},
}
</script>
<style scoped>
.children-div{}
</style>

子传父

利用$emit传值,父组件监听自定义事件,在子组件中通过触发该事件来传值:

子组件:

<template>
  <div class="children-div"></div>
</template>

<script>
export default {
  components: {},
  data() {
    return {
      msg: "test", //子组件需要传递给父组件的数据
    };
  },
  mounted() {
    this.getMsg();
  },
  methods: {
    getMsg() {
      this.$emit("get-msg", this.msg);
    },
  },
};
</script>
<style scoped>
.children-div {
}
</style>

父组件:

<template>
  <div class="parents-div">
    <!--触发自定义事件get-msg接收子组件数据-->
    <Children @get-msg="getMsg" />
  </div>
</template>

<script>
import Children from "./Children.vue"; //引入子组件
export default {
  components: { Children }, //注册子组件
  methods: {
    //获取到子组件传递过来的数据
    getMsg(msg) {
      console.log(msg);
    },
  },
};
</script>
<style scoped>
.parents-div {
}
</style>

vuex传值

vuex相当于一个公共仓库,保存着所有组件都能共用的数据,需要时可以直接使用,不需要考虑组件间是否有引用与被引用的父子关系。

扫描二维码推送至手机访问。

版权声明:本文由曦的博客发布,如需转载请注明出处。

本文链接:http://xiblogs.top:1111/?id=22

返回列表

上一篇:vue中使用sass

下一篇:vuex的使用

“vue组件间传值” 的相关文章

vue项目的创建

vue项目的创建

安装node1、检查node,未安装在这里(https://nodejs.org/dist/v16.14.0/node-v16.14.0-x64.msi )下载最新版安装。2、检查npm,node自带npm但不是最新版本,需要命令更新:npm install -g npm 安装vue脚手架1、在国...

vue打包后dist的使用

vue打包后dist的使用

发现问题vue项目完成打包出dist后准备打开index.html,发现居然页面是一片空白,f12一片报红。 分析问题经过多次网上查询后发现这是由于vue打包时,脚手架会帮你配置好大量参数,但其中路径publicPath被配置为了”/“,需要手动修改。 解决办法1、将vue.config.js中...

canvas实现图片标记

canvas实现图片标记

前言由于业务需求,需要有一个图片标记功能,其实就是对图片画框画线做标记,类似微信的图片编辑但是需要存下标记图及其标记的具体数据,。功能其实很简单,但刚开始的时候也是费了一些功夫的。我将原项目中该功能抽离出来单独写了一个demo,作为记录,同时你们在开发过程中有类似需求的话也可以参考一下该思路,其中有...

vue导出word文档

vue导出word文档

具体需求在我的项目中有一个功能需要导出word文档,在页面点击按钮后处理数据生成word文件,然后自动下载文档。 实现步骤 多番查询后发现前端导出word,使用docxtemplater(https://docxtemplater.com/ )较为方便。具体使用步骤如下: 安装docxte...

数据看板可视化

数据看板可视化

前言这段时间一直在做可视化,在我的项目中有一部分是电力巡检的数据可视化。其中的数据看板比较简单,我将其单独抽离出来形成一个demo,为保密demo中数据非真实数据。先看效果。 具体效果 链接相关 浏览链接:https://xiblogs.top/original/bigScreen/29/in...

纯前端实现图片验证码

前言之前业务系统中验证码一直是由后端返回base64与一个验证码的字符串来实现的,想了下,前端其实可以直接canvas实现,减轻服务器压力。 实现子组件,允许自定义图片尺寸(默认尺寸为100 * 40)与验证码刷新时间(默认时间为60秒)。同时暴露绘制验证码方法drawPic(),允许父组件直接调...

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。