vue 组件间的传值 + 路由守卫

一、路由守卫:https://blog.csdn.net/qq_26769677/article/details/101003337

全局前置守卫(beforeEnter)/路由独享(beforeEnter)/组件内的守卫(beforeRouteEnter、beforeRouteUpdate、beforeRouteLeave)

  • to:进入到哪个路由去
  • from:从哪个路由离开
  • next:路由的控制参数,常用的有next(true)和next(false)

二、组件间的传值

1. 父传子props、路由query、$ref、vuex

2. 子传父$emit、$ref、vuex

一:父传子query、props

①、props

父:通过监听父组件的name值

<template>
  <div class="hello">
    父组件:
    <input type="text" v-model='name'>
    <!-- 引入子组件 -->
    <child :inputName='name'></child>
  </div>
</template>

<script>
import child from './son'
export default {
  name: 'father',
  data () {
    return {
      name: '',
    }
  },
  components: {
    child
  }
}
</script>

子:通过子组件html部分的自定义属性,js的props的调用自定义属性值

<template>
  <div class="son">
    子组件:
    <span>{{inputName}}</span>
  </div>
</template>

<script>
export default {
  name: 'son',
  data () {
    return {
    }
  },
  props: {
    inputName: {
    type: String,
default: '儿子名字'
  }
} } </script>

②、利用location

父:用组件router-link的to的query,用组件<router-link :to="{path: '子组件地址', query:{ }}">

<template>
  <div>
    <router-link :to="{ path: '/meishi/mChildren', query: {fid: ‘儿子接着’}}">传给子</router-link>
  </div>
</template>

子:water监听$route

export default {
  name: 'meishiChildren',
  data () {

  },
  watch: {
    '$route' (to, from) {
     console.log(this.$route.query.fid)
    }
  },
  methods: {}
}

二、子传父

①、$emit

 子:通过v-on触发方法用this.$emit传给父信息

<template>
  <div class="hello">
    <input type="button" name="" id="" @click="chilCall()" value="子调父" /> 
  </div>
</template>

<script>
    export default {
        name: 'hello',
        'methods': {
            chilCall(pars) {
                this.$emit('newNodeEvent', '我是子元素传过来的')
            }
        }
    }
</script>

父:通过方法获取消息

<template>
  <div id="app">
    <hello @newNodeEvent="parentLisen" />
  </div>
</template>

<script>
    import hello from './son'
    export default {
        name: 'app',
        'components': {
            hello
        },
        methods: {
            parentLisen(evtValue) {    
                //evtValue 是子组件传过来的值
                alert(evtValue)
            }
        }
    }
</script>

 

②、$ref (vue的dom节点)   https://www.jianshu.com/p/3bd8a2b07d57

<template>
  <div id="app">
    <button @tap='showSon'></button>
    <hello ref="jjjjj" />
  </div>
</template>

<script>
    import hello from './son'
    export default {
        name: 'app',
        'components': {
            hello
        },
        methods: {
           showSon() {    
                //获取组件dom节点信息,下有_props属性等可访问
                console.log(this.$refs.jjjjj)
            }
        }
    }
</script>

正常的组件,或原始组件

参考:http://www.bslxx.com/m/view.php?aid=2220


三、插槽
https://www.cnblogs.com/chinabin1993/p/9115396.html
用slot替换组件里面的内容
具名插槽就是给插槽取名字,分开传

.sync Update
父: <son :visible.sync="childShow"/>
子:this.$emit("update:visible",false);
https://www.jianshu.com/p/b149f9fd8178

原文地址:https://www.cnblogs.com/lgyong/p/11570040.html