1. 通过路由带参数进行传值
- this.$router.push({
- path: '/conponentsB', query: {
- orderId: 123
- }
- }) // 跳转到 B
- this.$route.query.orderId // 在 B 组件拿到的参数
2. 通过设置 Session Storage 缓存的形式进行传递
- const orderData = {
- 'orderId': 123, 'price': 88
- }
- sessionStorage.setItem('缓存名称', JSON.stringify(orderData))
- const dataB = JSON.parse(sessionStorage.getItem('缓存名称')) // 在其他组件拿到 session Storage 缓存的值
3. 父组件向子组件传值
- // parant.vue
- <template>
- <div>
- <Child :number="number"></Child>
- </div>
- </template>
- <script>
- import Child form 'component/child'
- export default{
- component:{
- Child
- },
- data(){
- return {
- number:'123'
- }
- }
- }
- </script>
- // 在父组件引入子组件, 并把 number 传给子组件
- // Child.vue
- <template>
- <div>
- {{number}} // 显示父组件传来的值 123
- </div>
- </template>
- <script>
- export default{
- props:{ // 限制父组件传递过来的数据类型, 如果不符合就报错
- 'number':[Number,String],
- 'string':[String], // 可以传递多个值, 逗号隔开
- }
- }
- </script>
4. 子组件向父组件传值
- // Child.vue
- <template>
- <div>
- <button @click="add"> 点击 </button>
- <!-- 子组件通过触发 emit 给父组件传递数据 -->
- </div>
- </template>
- <script>
- export default{
- methods:{
- add(){ this.$emit('emitEvent','子组件传递给父组件的数据')
- }
- }
- }
- </script>
- // parant.vue
- <template>
- <div>
- <span>{{num}}<span>
- <Child @emitEvent= "setNum"></Child>
- <!-- 触发父组件的一个方法, 然后拿到子组件传过来的值, 再做其他操作 -->
- </div>
- </template>
- <script>
- import Child form 'component/child'
- export default{
- component:{
- Child
- },
- data(){
- return {
- num:''
- }
- },
- methods(){
- setNum(data){
- this.num = data // 子组件传递给父组件的数据
- }
- }
- }
- </script>
5. 大型项目用 vuex
具体怎么用 vuex, 可以简单大概了解下
https://www.jianshu.com/p/5f5700e9f43e
来源: http://www.jianshu.com/p/28ac49f5a99e