js

vue中的prop

2018-12-05  本文已影响18人  回不去的那些时光

学习vue有一段时间了,也写了一些东西。今天看文档突然看到了一个好玩的东西,那就是prop。prop的作用是父组件中引用了子组件并给子组件加了一个属性,这个属性可以是静态的,可以是动态的,可以是数字,可以是字符串,可以是数组,还可以是对象。接下来就展示改怎么用。

传静态的属性

子组件:

<template>
  <div>
    <h1>{{ msg }}</h1>
  </div>
</template>

<script>
export default {
  props: ["msg"]
}
</script>

父组件:

<template>
  <div id="app">
    <HelloWorld msg="hello"/>
  </div>
</template>

<script>
import HelloWorld from "./components/HelloWorld.vue";

export default {
  components: {
    HelloWorld
  }
};
</script>

好了,这样就完成了一个最简单的使用prop接收父元素的值

传动态字符串

子组件

<template>
  <div>
    <h1>{{ msg }}</h1>
  </div>
</template>

<script>
export default {
  props: ["msg"]
}
</script>

父组件

<template>
  <div id="app">
    <HelloWorld :msg="hello"/>
  </div>
</template>

<script>
import HelloWorld from "./components/HelloWorld.vue";

export default {
  components: {
    HelloWorld
  },
  data() {
    return {
      hello: "hello world"
    }
  }
};
</script>

可以看到,子组件我未做任何修改,只是在父组件做了一些修改

传动态数组

子组件

<template>
  <div>
    <ul>
      <li v-for="item in msg" :key="item">
        {{ item }}
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  props: ["msg"]
}
</script>

父组件

<template>
  <div id="app">
    <HelloWorld :msg="hello"/>
  </div>
</template>

<script>
import HelloWorld from "./components/HelloWorld.vue";

export default {
  components: {
    HelloWorld
  },
  data() {
    return {
      hello: ["aa", "bb", "cc"]
    }
  }
};
</script>

传动态对象

子组件

<template>
  <div>
    <h1>{{ msg.id }}</h1>
    <h2>{{ msg.name }}</h2>
  </div>
</template>

<script>
export default {
  props: ["msg"]
}
</script>

父组件

<template>
  <div id="app">
    <HelloWorld :msg="hello"/>
  </div>
</template>

<script>
import HelloWorld from "./components/HelloWorld.vue";

export default {
  components: {
    HelloWorld
  },
  data() {
    return {
      hello: {
        id: 1,
        name: "hello dj"
      }
    }
  }
};
</script>

对prop的状态进行验证

prop的状态可以为

<template>
  <div>
    <h1>{{ num }}</h1>
    <h1>{{ msg }}</h1>
    <h1>{{ obj.id }}</h1>
    <h2>{{ obj.name }}</h2>
    <ul>
      <li v-for="item in arrs" :key="item">
        {{ item }}
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  props: {
    num: {
      type: Number
    },
    msg: {
      type: String
    },
    arrs: {
      type: Array
    },
    obj: {
      type: Object
    }
  }
}
</script>

父组件

<template>
  <div id="app">
    <HelloWorld :num="num" :msg="hello" :arrs="arr" :obj="post"/>
  </div>
</template>

<script>
import HelloWorld from "./components/HelloWorld.vue";

export default {
  components: {
    HelloWorld
  },
  data() {
    return {
      num: 10,
      hello: "hello world",
      arr: ["aa","bb","cc"],
      post: {
        id: 1,
        name: "hello dj"
      }
    }
  }
};
</script>

上面演示了Number,String,Array,object的用法

上一篇 下一篇

猜你喜欢

热点阅读