vue.js----父组件向子组件传值 ,子组件执行父组件方法

古城微笑少年丶 2023-06-08 14:55 80阅读 0赞

1,父组件向子组件传值,可以是:在使用子组件的时候,将需要传递的数据,通过属性绑定的形式,传递给子组件;在子组件中通过props进行接收;可以是数组形式接收,props:[‘val’];也可以是对象形式接收:props:{ val:{type:”string”,default:”Hello”}} ;

父组件代码:

  1. <template>
  2. <div style="background:red;margin-top:20px;">
  3. <child3 v-bind:msg="val"></child3>
  4. </div>
  5. </template>
  6. <script>
  7. import child3 from './child3'
  8. export default {
  9. data () {
  10. return {
  11. val:'HelloWorld'
  12. }
  13. },
  14. components:{
  15. 'child3':child3
  16. }
  17. }
  18. </script>

子组件代码:

  1. <template>
  2. <div style="background:skyblue;">
  3. 这是父组件传递过来的数据:{
  4. {msg}}
  5. </div>
  6. </template>
  7. <script>
  8. export default {
  9. data () {
  10. return {}
  11. },
  12. props:['msg']
  13. }
  14. </script>

这样在页面初始化后,父组件中的数据 HelloWorld 将传入到子组件中,但是也只能传递一次;可以在父组件中添加一些事件来改变子组件中的数据;比如添加鼠标点击事件;父组件代码修改之后如下:

  1. <template>
  2. <div style="background:red;margin-top:20px;">
  3. <button @click="dianwo">点我向子组件传值</button>
  4. <child3 v-bind:msg="val"></child3>
  5. </div>
  6. </template>
  7. <script>
  8. import child3 from './child3'
  9. export default {
  10. data () {
  11. return {
  12. val:1
  13. }
  14. },
  15. components:{
  16. 'child3':child3
  17. },
  18. methods:{
  19. dianwo(){
  20. this.val ++
  21. }
  22. } }
  23. </script>

当在父组件中点击按钮之后,改变val的值,同时,子组件中的值也就改变了;

2,子组件中执行父组件的方法也是使用事件绑定机制, 使用 v-on (简写@) 在组件上绑定一个自定义属性之后,子组件中可以通过 this.$emit(“methodName”,val) 方式执行方法,

父组件代码:

  1. <template>
  2. <div style="background:red;margin-top:20px;">
  3. <child3 v-bind:msg="val" @action="fromChild"></child3>
  4. </div>
  5. </template>
  6. <script>
  7. import child3 from './child3'
  8. export default {
  9. data () {
  10. return {
  11. val:1
  12. }
  13. },
  14. components:{
  15. 'child3':child3
  16. },
  17. methods:{
  18. fromChild(val){
  19. console.log(val)
  20. }
  21. } }
  22. </script>

子组件代码;

  1. <template>
  2. <div style="background:skyblue;">
  3. <button @click="active">点我执行父组件方法</button>
  4. </div>
  5. </template>
  6. <script>
  7. export default {
  8. data () {
  9. return {
  10. }
  11. },
  12. props:['msg'],
  13. methods:{
  14. active(){
  15. this.$emit("action","action parent method")
  16. }
  17. }
  18. }
  19. </script>

说明:在父组件中通过在引入的子组件中绑定了一个action,属性值是 fromChild ,就是该组件中的方法名,即将该组件中的方法传递到子组件中,在子组件中 this.$emit(“action”,”action parent method”) 可以执行自定义事件action, (第一个参数是自定义事件名,第二个参数是传递的参数); 执行 this.$emit(“action”,”action parent method”) 后,会执行自定义事件对应的方法fromChild;

发表评论

表情:
评论列表 (有 0 条评论,80人围观)

还没有评论,来说两句吧...

相关阅读