三种传值方式:父传子 子传父 非父子
- 父传子
- 子传父
- 非父子
父组件向子组件传值
<!DOCTYPE html>
<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">
Vue.component('father',{
template:`
<ul>
<li v-for="temp in list">{{temp}}</li>
<son @clic="get"></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>
效果图演示效果
子组件传父组件传值
在子组件里面定义数据 使用$emit来进行自定义事件的触发 以及数据的发送
非父子之间的传值
<!DOCTYPE html>
<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>child1</li></ul></div>
)
}
componentWillMount(){
window.localStorage.setItem('site','haomahaode')
}
}
class Child2 extends React.Component{
constructor(){
super()
}
render(){
return (
<div><ul><li>child2</li></ul></div>
)
}
componentWillMount(){
console.log(window.localStorage.getItem('site'))
}
}
ReactDOM.render(
<div><Child1></Child1>
<Child2></Child2></div>
,
document.getElementById("app")
)
</script>
</html>