父传子:Props 子传父:子:$emit(eventName) 父$on(eventName) 父访问子:ref 非父子组件通信 :https://vuefe.cn/guide/components.html#非父子组件通信 vue2.0 移除:1.$dispatch() 2.$broadcast() 3.events
新的ES6写法等同于旧的写法
//新的ES6 data () { return { title: 'this is a title!' } } //旧的写法 data: function (){ return { title: 'this is a title!' } }v-html 解析渲染html标签
store.js
const STORAGE_KEY = 'todos-vuejs' export default { fetch () { return JSON.parse(window.localStorage.getItem(STORAGE_KEY) || '[]') }, save (items) { window.localStorage.setItem(STORAGE_KEY, JSON.stringify(items)) } } v-bind:class简写:classv-on:click简写@clickv-on:keyup.enter简写@keyup.enter 回车keyup事件v-model 双向绑定经 JSON.parse(str) 得到:
Object: age:"23" name:"cpf" _proto_:Objectps:单引号写在{}外,每个属性都必须双引号,否则会抛出异常
stringify用于从一个对象解析出字符串,例如var a={a:1,b:2}
经 JSON.stringify(a)得到:
“{“a”:1,"b":2}”
使用 $on() 监听事件;
使用 $emit()在它上面触发事件;
使用 $dispatch()派发事件,事件沿着父链冒泡;
使用 $broadcast()广播事件,事件向下传导给所有的后代。
父组件
<component-a msgfromfather='you die!!!!'></component-a>子组件
<template> <div class="hello"> <h1>{{ msgfromfather }}</h1> <button v-on:click="onClickMe">click!</button> </div> </template> <script> export default { data () { return { } }, props: ['msgfromfather'], methods: { onClickMe () { console.log(this.msgfromfather) } } } </script> <style scoped> h1 { color: #42b983; } </style> props监听父组件传递过来的信息传递过来后,可直接引用,就如已经传递过来数据塞到data父组件
<template> <button v-on:click="talkToMyBoy('be a good boy')">talkToMyBoy</button> </div> </template> <script> import Store from './store' import ComponentA from './components/componentA' export default { components: { ComponentA }, methods: { talkToMyBoy (msg) { //console.log(msg); this.$broadcast('onAddnew',msg) } } } </script>子组件
<template> <div class="hello"> <h1>{{ listentomyfather }}</h1> </div> </template> <script> export default { data () { return { listentomyfather: 'Hello from componentA!' } }, events: { 'onAddnew' (msg) { //console.log(msg) this.listentomyfather = msg } } } </script>父组件
<template> <div id="app"> <p>child tell me: {{childWords}}</p> <component-a v-on:child-tell-me-something='listenToMyBoy'></component-a> </div> </template> <script> import Store from './store' import ComponentA from './components/componentA' export default { components: { ComponentA }, data () { return { childWords: '' } }, methods: { listenToMyBoy (msg) { this.childWords = msg } } } </script>子组件
<template> <div class="hello"> <button v-on:click="onClickMe">talktomyfather</button> </div> </template> <script> export default { methods: { onClickMe () { this.$dispatch('child-tell-me-something',this.msg) } } } </script>父组件
<template> <div id="app"> <p>child tell me: {{childWords}}</p> <component-a></component-a> </div> </template> <script> import Store from './store' import ComponentA from './components/componentA' export default { components: { ComponentA }, data () { return { childWords: '' } }, events: { 'child-tell-me-something' (msg) { this.childWords = msg } } } </script>