Vue基础

96 阅读1分钟

1、vue不同组件之间传递值

情况一:父组件-->子组件

父组件向子组件进行传值props

父组件:

       <template>
        <div>
          <!-- 引入子组件 -->
          <child :inputName="name"></child>
        </div>
      </template>
      <script>
        import child from './child'
        export default {
          components: {
            child
          },
          data () {
            return {
              name: ''
            }
          }
        }
      </script>

子组件

      <template>
        <div>
          子组件:
          <span>{{inputName}}</span>
        </div>
      </template>
      <script>
        export default {
          // 接受父组件的值
          props: {
            inputName: String,
            required: true
          }
        }
      </script>
情况二:子组件-->父组件

子组件向父组件传值$emit,父组件通过子组件的ref属性获取值 子组件

        <template>
          <div>
            子组件:
            <span>{{childValue}}</span>
            <!-- 定义一个子组件传值的方法 -->
            <input type="button" value="点击触发" @click="childClick">
          </div>
        </template>
        <script>
          export default {
            data () {
              return {
                childValue: '我是子组件的数据'
              }
            },
            methods: {
              childClick () {
                // childByValue是在父组件on监听的方法
                // 第二个参数this.childValue是需要传的值
                this.$emit('childByValue', this.childValue)
              }
            }
          }
		</script>

父组件:

       <template>
        <div>
          父组件:
          <span>{{name}}</span>
          <!-- 引入子组件 定义一个on的方法监听子组件的状态-->
          <child v-on:childByValue="childByValue"></child>
        </div>
      </template>
      <script>
        import child from './child'
        export default {
          components: {
            child
          },
          data () {
            return {
              name: ''
            }
          },
          methods: {
            childByValue: function (childValue) {
              // childValue就是子组件传过来的值
              this.name = childValue
            }
          }
        }
      </script>
情况三:不同页面

通过router

发送数据页面

    this.$router.push({
          path:'/views/rules',
          query:{
            explainMsg: this.awardDetail.explainMsg
          }
        })

接收数据页面

     <script>
        export default {
          data() {
            return {
              explainMsg: ''
            };
          },
          created(){
            this.explainMsg = this.$route.query.explainMsg;
          },
          methods: {
            onBackPressed() {
              // 点击返回按钮,向后跳转
              this.$router.back();
            }
          }
        };
     </script>