Vue 父子組件通信傳值(子組件中使用父組件中的數(shù)據(jù))

作者:辰風沐陽 閱讀:1738 發(fā)布時間:2020-08-02 上次更新:2022-01-04

1. 父傳子 props


父組件中的數(shù)據(jù)傳遞給子組件

官方文檔:通過-Prop-向子組件傳遞數(shù)據(jù)

  1. props: ['movies'],
  2. props: {
  3. movies: Array
  4. },
  5. props: {
  6. movies: {
  7. type: Array,
  8. default: [],
  9. required: true
  10. }
  11. },

props 的駝峰標識

  1. <cpn :c-info="userinfo"></cpn>
  2. props: {
  3. cInfo: {
  4. type: Object,
  5. default: { name: 'liang' }
  6. }
  7. }

2. 使用示例


  1. <div id="app">
  2. <parent :article="art"></parent>
  3. </div>
  4. <script>
  5. var child = {
  6. template: `<p>{{ author }}</p>`,
  7. props: ['author']
  8. }
  9. var par = {
  10. template: `<div>
  11. {{ article.title }}
  12. <child :author="article.author"></child>
  13. </div>
  14. `,
  15. props: ['article'],
  16. components: {
  17. child: child
  18. }
  19. }
  20. let vm = new Vue({
  21. el: '#app',
  22. data: {
  23. art: {
  24. title: 'liang',
  25. content: 'itqaq.com',
  26. author: '辰風沐陽'
  27. }
  28. },
  29. components: {
  30. parent: par
  31. }
  32. })
  33. </script>

3. 實戰(zhàn)文章列表


  1. <div id="app">
  2. <art-list :article="arts"></art-list>
  3. </div>
  4. <script>
  5. var artis = {
  6. template: `
  7. <ul>
  8. <li v-for="art in article">
  9. <h1>{{ art.title }}</h1>
  10. <img :src="art.img" style="width:200px;">
  11. <p>{{ art.content }}</p>
  12. </li>
  13. </ul>
  14. `,props: ['article']
  15. }
  16. let vm = new Vue({
  17. el: '#app',
  18. data: {
  19. arts: [
  20. {
  21. title: '01',
  22. img: 'img/01vue.jpg',
  23. content: '01content',
  24. },
  25. {
  26. title: '02',
  27. img: 'img/01vue.jpg',
  28. content: '02content'
  29. },
  30. ]
  31. },
  32. components: {
  33. 'art-list': artis
  34. }
  35. })
  36. </script>

標簽: vue