vue2.0的三种常用传值方式,并且如何实现?

三种传值方式:父传子 子传父 非父子

  1. 父传子
  2. 子传父
  3. 非父子

vue2.0的三种常用传值方式,并且如何实现?_第1张图片

父组件向子组件传值


<html>
    <head>
        <meta charset="UTF-8">
        <title>子向父亲进行传值title>
        <script src="vue.js" type="text/javascript" charset="utf-8">script>
    head>
    <body>
        <div id="app">
            <father>father>
        div>
    body>
    <script type="text/javascript">

//      子组件如何向父组件里面进行传值
//      1.首先创建两个组件一个是子组件一个是父组件
//      2.在子组件里面定义数据 使用$emit来进行自定义事件的触发 以及数据的发送
//      3.在父组件里面使用v-on绑定的自定义事件 事件触发 并且执行事件处理函数  通过函数的参数来接受传递过来的数据


        Vue.component('father',{
            template:`
            
    <li v-for="temp in list">{{temp}}</li> son> ul> `, data(){ return{list:[]} }, methods:{ get:function(msg){ this.list.push(msg) } } }) Vue.component('son',{ template:` <div> <input type="text" v-model="inputval" /> <button @click="clik">父亲向子传数据button> div> `, data(){ return{ inputval:'' } }, methods:{ clik(){ this.$emit('clic',this.inputval) this.inputval="" } } }) var app=new Vue({ el:"#app" }) script> html>

效果图演示效果

vue2.0的三种常用传值方式,并且如何实现?_第2张图片

子组件传父组件传值

在子组件里面定义数据 使用$emit来进行自定义事件的触发 以及数据的发送

非父子之间的传值

vue2.0的三种常用传值方式,并且如何实现?_第3张图片


<html>
    <head>
        <meta charset="UTF-8">
        <title>非父子组件之间的传值title>
        <script src="js/react.development.js" type="text/javascript" charset="utf-8">script>
<script src="js/react-dom.development.js" type="text/javascript" charset="utf-8">script>
        <script src="js/babel.min.js" type="text/javascript" charset="utf-8">script>
        <script src="js/axios.js" type="text/javascript" charset="utf-8">script>
    head>
    <body>
        <div id="app">div>
    body>
    <script type="text/babel">
        class Child1 extends React.Component{
        constructor(){
            super()
         }
            render(){
                return   (
                    <div><ul><li>child1li>ul>div>
                )
            }
            componentWillMount(){
                window.localStorage.setItem('site','haomahaode')
            }
        }

        class Child2 extends React.Component{

         constructor(){
            super()
         }

            render(){
                return   (
                    <div><ul><li>child2li>ul>div>
                )
            }
            componentWillMount(){
                console.log(window.localStorage.getItem('site'))
            }
        }
        ReactDOM.render(
            <div><Child1>Child1>
            <Child2>Child2>div>
            ,
            document.getElementById("app")
        )
    script>
html>

你可能感兴趣的:(vue2.0的三种常用传值方式,并且如何实现?)