子组件使用父组件传的值

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

子组件使用父组件传的值

我是小路路呀   2022-05-28 我要评论

子组件使用父组件传过来的值

父组件

<alarmstatistics :roless.sync="role"></alarmstatistics>
  import alarmstatistics from "./alarmstatistics.vue";
  components: {
    alarmstatistics,
  },

子组件

  props: ["roless"],
  
  data() {
    return {
      role:this.roless,
  },
  
  mounted() {
    if(this.role==3){
      this.chartY = "9.5%";
    }else{
      this.chartY = "18%";
    }
  },

如果是使用父组件接口返回来的值,在html中直接使用

  props: ["infoDatac"],
      <li
        v-for="(item,i) in infoDatac.notice.admitted"
        :key="'A'+ i"
      >
        <div>申请单号:{{ item.applyCode }}</div>
        <div>使用时间:{{ item.useTime }}</div>
        <span>{{ item.title }}</span>
      </li>

vue子组件调用父组件数据

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title></title>
        <script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
    </head>
    <body>
        <div class="" id="myVue">
            <my-component>
            </my-component>
        </div>
        <!--子组件-->
        <template id="child"  >
            <div id="">
                <div @click='changedata'>子组件:{{data}}</div>
            </div>
        </template>
        <!--父组件-->
        <template id="father">
            <div>
                <mycomponent-child v-bind:data="str"></mycomponent-child>
            </div>
        </template>
    </body>
    <script type="text/javascript" charset="utf-8">
        /*在父组件中的数据str,
         * 将父组件的数据绑定到子组件的属性data上
         * 然后在子组件中就可以通过props接收到,
         * 这样在子组件中就可以使用变量 this.data1访问到 父组件的 str1对应的值了。
         */
        //当点击子组件,触发子组件的changedata方法,通过this.data = "父组件值被子组件修改了";改变了父级的str的值
        //通过  this.$parent.fn()访问父组件的方法fn()。
        var child={
            props:["data"],
            template:"#child",
            data:function(){
                return{
                    str:"我是子组件数据"
                }
            },
            methods:{
                changedata:function(){
                    this.data = "父组件值被子组件修改了";
                    this.$parent.fn();
                }
           }
        }
        
        /*父组件*/
        var father={
            template:"#father",
            data:function(){
                return{
                    str:"我是父组件数据"
                }
            },
            methods:{
                fn:function(){
                    alert("我是父组件方法")
                }
            },
            components:{
                "mycomponentChild":child
            }
        }
        
        vm=new Vue({
            //el:"#myVue",
            components:{
                "myComponent":father
            }
        }).$mount('#myVue');
        
    </script>
</html>

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。 

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们