vue 組件傳值、頁面(路由)傳值


一、組件傳值

1、父組件——>子組件(屬性傳值)

在父組件頁面引入子組件並在,兒子身上綁定屬性 :list = "list"

父組件頁面data中填寫要傳遞的值 list[a,b,c]

子組件頁面接受

props: {
  list: {
    type: Array,
    default() {
    return [];
    }
  }
}
子組件頁面就可以拿到值了 {{list[0]}}

2、子組件——》父組件(事件傳值)

子組件中定義事件:

<div :class="['btn', show ? 'btn1' : '']" @click=" showMenu"></div>;
通過$emit觸發,第一個參數是事件名 第二個是要傳遞的數據;
showMenu() {
      this.show = !this.show;
       this.$emit(' showMenu', this.show);
    },
在父組件頁面引入子組件並在,兒子身上綁定 觸發的事件名 @ showMenu="toShowMenu";
通過參數接受傳過來數據 
toShowMenu(v) {
     console.log(v)
   }
 
另外:this.$emit 也可以只傳遞一個事件名,不傳遞值。也就是只在子組件觸發一個事件傳過去。父組件通過該事件操作自己身上的值。。
子組件代碼:
<van-button class="prev" type="default" @click="toPrev">上一項</van-button>

父組件代碼:
<kcbl @toPrev="currentStep--;"/>

 3、父組件直接引用子組件身上的方法 ref。


子組件:

<template>
  <div>
    <!-- 把傳遞過來的參數進行頁面渲染 -->
    <span>我是引用模板中的文字的小憨憨</span>
  </div>
</template>

<script>
export default {
  data() {
    return {
      hello: '我才有一個參數需要你進行接受'
    };
  }
};
</script>

父組件:

<template>
  <div class="content">
    <div class="text-area">
      <button @click="toGo">點擊我哦</button>
    </div>
    <child-1 ref="hellosss"></child-1>
  </div>
</template>

<script>
import child1 from './child1';
export default {
  components: {
    child1
  },
  data() {
    return {
      title: 'Hello'
    };
  },
  methods: {
    toGo() {
      //拿到父組件的hello變量
      console.log('我是接受參數的', this.$refs.hellosss.hello);
      //輸出:我是接受參數的 我才有一個參數需要你進行接受
    }
  },
  mounted() {
    //拿到父組件的hello變量
    console.log('我是接受參數的', this.$refs.hellosss.hello);
  },
};
</script>

 

 

參考: https://segmentfault.com/a/1190000011882494


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM