vue2中的插槽使用以及Vuex的使用

插槽分为默认插槽,定名插槽还有作用域插槽

一.默认插槽,定名插槽

//app.vue
<template>
<div class="container">
    <CategoryTest title="美食" :listData="foods">
        <img slot="center" src="https://img2.baidu.com/it/u=381412217,2118678125&fm=253&fmt=auto&app=138&f=JPEG?w=889&h=500" alt="">
        <a slot="footer" href="www.baidu.com">更多美食</a>
    </CategoryTest>

    <CategoryTest title="游戏" :listData="games">
        <ul slot="center">
            <li v-for="(item,index) in games" :key="index">{{item}}</li>
        </ul>
        <div class="foot" slot="footer">
        <a  href="www.baidu.com">单机游戏</a>
        <a href="www.baidu.com">网络游戏</a>
        </div>
    </CategoryTest>

    <CategoryTest title="电影" :listData="films">
       <iframe slot="center" height=498 width=510 src='https://player.youku.com/embed/XNTE4MDgwMTAzMg==' frameborder=0></iframe>
        <template v-slot:footer>
             <div class="foot">
            <a href="www.baidu.com">经典</a>
            <a href="">热门</a>
            <a href="">推荐</a>
            <h4>欢迎前来观影</h4>
            </div>
        </template>

    </CategoryTest>
</div>
</template>
<script>
import CategoryTest from './components/CategoryTest.vue'
export default({
    name:'App',
    components:{CategoryTest},
    data() {
        return {
            foods:['火锅','烧烤','小龙虾','牛排'],
            games:['红色警戒','炉石传说','模拟飞行','战地','cod'],
            films:['教父','楚门的世界','情书','末代皇帝']
        }
    },
})
</script>
<style scoped>
.container,.foot{
    display: flex;
    justify-content: space-around;
}
iframe{
    width: 80%;
    height: 50%;
    margin: 0 auto;
}
.foot h4{
    text-align: center;
}
</style>						
//categoryTest.vue
<template>
    <div class="category">
        <h3>{{title}}分类</h3>
        <!-- slot 定义一个插槽(挖个坑,等着组件的使用者进行填充) -->
        <slot name="center">我是一个默认值,当使用者没有传递集体结构时,我会出现</slot>
        <!-- 为slot命名name:定义一个具名插槽 -->
        <slot name="footer">我是一个默认值,当使用者没有传递集体结构时,我会出现</slot>
    </div>
</template>

<script>
export default {
    name:'CategoryTest',
    props:['title']
}
</script>

<style>
    .category{
         background-color: rgb(12, 207, 207);
        width: 300px;
        height: 300px;
    }
    .category h3{
        text-align: center;
        background-color: yellow;
    }
    img{
        width: 100%;
    }
</style>

 效果如图:

二. 作用域插槽

//app.vue
<template>
<div class="container">
    <CategoryTest title="游戏">
        <template scope="atguigu">
            <div>
                <ul>
                    <li v-for="(g,index) in atguigu.games" :key="index">{{g}}</li>
                </ul>
            </div>
        </template>
    </CategoryTest>
        <CategoryTest title="游戏">
        <template scope="atguigu">
            <div>
                <ol>
                    <li style="color:red" v-for="(g,index) in atguigu.games" :key="index">{{g}}</li>
                </ol>
                <h4>{{atguigu.x}}</h4>
            </div>
        </template>
    </CategoryTest>
</div>
</template>
<script>
import CategoryTest from './components/CategoryTest.vue'
export default({
    name:'App',
    components:{CategoryTest},
})
</script>
<style scoped>
.container,.foot{
    display: flex;
    justify-content: space-around;
}
iframe{
    width: 80%;
    height: 50%;
    margin: 0 auto;
}
.foot h4{
    text-align: center;
}
</style>

//categoryTest.vue
<template>
    <div class="category">
        <h3>{{title}}分类</h3>
        <slot :games="games" :x='msg'>我是默认内容</slot>
    </div>
</template>

<script>
export default {
    name:'CategoryTest',
    props:['title'],
    data() {
        return {
             games:['红色警戒','炉石传说','模拟飞行','战地','cod'],
             msg:'时间啊,你是多么的美丽'
        }
    },
}
</script>

<style>
    .category{
         background-color: rgb(12, 207, 207);
        width: 300px;
        height: 300px;
    }
    .category h3{
        text-align: center;
        background-color: yellow;
    }
    img{
        width: 100%;
    }
</style>

 如图所示:

三.vuex

1.概念:专门在Vue中实现集中式状态(数据)管理的一个Vue插件,对vue应用中多个组件的共享状态进行集中式的管理(读/写),也是一种组件间通信的方式,且适用于任意组件通信
2.什么时候使用Vuex

  • 多个组件依赖于同一状态
  • 来自不同组件的行为需要变更同一状态

 1.搭建vuex环境

// 该文件用于创建vuex中最为核心的store
import Vue from 'vue'
// 引入Vuex
import Vuex from 'vuex'
// 使用Vuex插件
Vue.use(Vuex)
// 创建并暴露store
const store= new Vuex.Store({
    // 准备actions--用于响应组件中的动作
   actions:{
  
},
// 准备mutations--用于to操作数据(state)
   mutations:{
 
},

// 准备state--用于存储数据
state:{
    
},
//准备action--用于异步操作数据  
})
export default store
2.在main.js中创建vm时传入store配置项
....
//引入store
import store from './store'
//创建vm
new Vue({
    el:'#app',
    render:h=>app,
    store
})

 如下是个案例:

2.求和案例vue版本

//app.vue
<template>
<div>
    <count-add></count-add>
</div>
</template>
<script>
import CountAdd from "./components/CountAdd.vue"
export default({
    name:'App',
    components:{CountAdd},
})
</script>
<style scoped>

</style>

//coutadd.vue
<template>
  <div>
      <h1>当前求和为:{{sum}}</h1>
      <select v-model="n">
          <option :value="1">1</option>
          <option :value="2">2</option>
          <option :value="3">3</option>
      </select>
      <button @click="increment">+</button>
      <button @click="decrement">-</button>
      <button @click="incrementOdd">当前求和为奇数再加</button>
      <button @click="incrementWait">等一等再加</button>
  </div>
</template>

<script>
export default {
    name:'CountAdd',
    data() {
        return {
            n:1,//用户选择的数字
            sum:0//当前的和
        }
    },
    methods: {
        increment(){
            this.sum+=this.n
        },
        decrement(){
            this.sum-=this.n
        },
        incrementOdd(){
            if(this.sum%2!=0){
                this.sum+=this.n
            }
        },
        incrementWait(){
            setTimeout(()=>{
                this.sum+=this.n
            })
        }
    },
}
</script>

<style scoped>
    button{
        margin-left:5px ;
    }
</style>

3.求和案例vuex版本

//main.js文件
import Vue from 'vue'
import App from './app.vue'
// 引入store
import store from './store/index'
// 关闭Vue的生产提示
Vue.config.productionTip = false

new Vue({
  store,
  render: h => h(App),
  beforeCreate(){
    Vue.prototype.$bus=this
  }
}).$mount('#app')

//store.js文件
// 该文件用于创建vuex中最为核心的store
import Vue from 'vue'
import countOption from './count'
import PersonOption from './person'
// 引入Vuex
import Vuex from 'vuex'
// 使用Vuex插件
Vue.use(Vuex)
// 创建并暴露store
const store= new Vuex.Store({
    modules:{
        countAbout:countOption,
        personAbout:PersonOption
    }
})
export default store
//count.js文件
const countOption={
    namespaced:true,
    actions:{
        jiaOdd:function(context,value){
            console.log('action中的jiaOdd被调用了',value)
            if(context.state.sum%2){
                context.commit('JIA',value)
            }
        },
        jiaWait:function(context,value){
            console.log('action中的jiaWait被调用了',value)
            setTimeout(() => {
                context.commit('JIA',value)
            }, 500);
        },
    },
    mutations:{
        JIA(state,value){
            console.log('mutations中的JIA被调用了',value)
            state.sum+=value
        },
        JIAN(state,value){
            console.log('mutations中的JIAN被调用了',value)
            state.sum-=value
        },
    },
    state:{
        sum:0,//当前的和
        name:'绘梨',
        hobby:'爱看电影的',
    },
    getters:{
        bigSum(state){
            return state.sum*10
        }
    }
}
export default countOption
//person.js
import axios from 'axios'
import { nanoid } from 'nanoid'
const PersonOption={
    namespaced:true,
    actions:{
        add_personWang(context,value){
            if(value.personName.indexOf('王')===0){
                context.commit('add_person',value)
            }else{
                alert('添加的人名不姓王')
            }
        },
        addPersonServer(context){
            axios.get('https://api.uixsj.cn/hitokoto/get?type=social').then(
                Response=>{
                    context.commit('add_person',{id:nanoid(),personName:Response.data})
                },
                error=>{
                    alert(error.message)
                }
            )
        }
    },
    mutations:{
        add_person(state,value){
            console.log('mutations中的add_person被调用了')
            state.personList.unshift(value)
        }
    },
    state:{
        personList:[
            {id:'001',personName:'电次'}
        ]
    },
    getters:{
        firstPersonName(state){
            return state.personList[0].personName
        }
    }
}
export default PersonOption

在Visual Studio Code中工作区中:

我们有一个store命名的文件夹里面有:

  • person.js
  • count.js
  • index.js

4.​ (模块化设计)

//app.vue
<template>
<div>
    <count-add></count-add>
    <person-add></person-add>
</div>
</template>
<script>
import CountAdd from "./components/CountAdd.vue"
import personAdd from './components/personAdd.vue'
export default({
    name:'App',
    components:{CountAdd,personAdd},
})
</script>
<style scoped>

</style>
//countadd.vue
<template>
  <div>
      <h1>当前求和为:{{sum}}</h1>
      <h1>{{hobby}}{{name}}</h1>
      <h1>当前求和放大10倍为{{bigSum}}</h1>
      <h1 style="color:red">person组件的总人数是:{{personList.length}}</h1>
      <select v-model="n">
          <option :value="1">1</option>
          <option :value="2">2</option>
          <option :value="3">3</option>
      </select>
      <button @click="increment(n)">+</button>
      <button @click="decrement(n)">-</button>
      <button @click="incrementOdd(n)">当前求和为奇数再加</button>
      <button @click="incrementWait(n)">等一等再加</button>
  </div>
</template>

<script>
import {mapState,mapGetters,mapMutations,mapActions} from 'vuex'
export default {
    name:'CountAdd',
    data() {
        return {
            n:1,//用户选择的数字
        }
    },
    methods: {
        //借助mpaMutations生成对应的方法,方法中对调用commit求联系mutation
        ...mapMutations('countAbout',{increment:'JIA',decrement:'JIAN'}),
        //借助mpaMutations生成对应的方法,方法中对调用commit求联系mutation
        // ...mapMutations(['JIA','JIAN'])需要将上面的函数名换成同名
        ...mapActions('countAbout',{incrementOdd:'jiaOdd',incrementWait:'jiaWait'})
         // ...mapAction(['JIAOdd','JIANWait'])需要将上面的函数名换成同名
    },
    computed:{
        ...mapState('countAbout',['sum','name','hobby']),
        ...mapState('personAbout',['personList']),
        // 借助mapState生成计算属性,从state中读取数据(对象写法)
        // ...mapState({sum:'sum',hobby:'hobby',name:'name'}),
        // 借助mapState生成计算属性,从state中读取数据(数组写法)
        // ...mapState(['sum','name','hobby','personList']),
        // 借助mapGetters生成计算属性,从Getters中读取数据(对象写法)
        // ...mapGetters({bigSum:'bigSum'})
        // 借助mapGetter生成计算属性,从Getters中读取数据(数组写法)
        ...mapGetters('countAbout',['bigSum'])
    }
}
</script>

<style scoped>
    button{
        margin-left:5px ;
    }
</style>
//personadd.vue
<template>
  <div>
      <h1>人员列表</h1>
      <h1 style="color:red">count组件的求和为:{{sum}}</h1>
      <h1>列表中第一个人的名字是{{firstPersonName}}</h1>
      <input type="text" placeholder="请输入名字" v-model="name">
      <button @click="add">添加</button>
      <button @click="addWang">添加一个姓王的人名</button>
      <button @click="addPersonServer">添加一个人,名字随机</button>
      <ul>
          <li v-for="p in personList" :key="p.id">
            {{p.personName}}
          </li>
      </ul>
  </div>
</template>

<script>
import {nanoid} from 'nanoid'
import {mapState} from 'vuex'
export default {
    name:'personAdd',
    data() {
        return {
            name:''
        }
    },
    methods: {
        add(){
            const personObj={id:nanoid(),personName:this.name}
            this.$store.commit('personAbout/add_person',personObj)
            this.name=''
        },
        addWang(){
            const personObj={id:nanoid(),personName:this.name}
            this.$store.dispatch('personAbout/add_personWang',personObj)
            this.name=''
        },
        addPersonServer(){
            this.$store.dispatch('personAbout/addPersonServer')
        }
    },
    computed:{
        ...mapState('personAbout',['personList']),
        ...mapState('countAbout',['sum']),
        firstPersonName(){
            return this.$store.getters['personAbout/firstPersonName']
        }
    }
}
</script>

<style>

</style>

如图所示:

5.vuex模块化+命名空间

目的:让代码更加好维护,让多种数据分类更加明确

 步骤一:修改store.js

const countAbout={
    namespaced:true,//开启命名空间
    state:{},
    mutation:{},
    action:{},
    getters{}
}
const PersonAbout={
    namespaced:true,//开启命名空间
    state:{},
    mutation:{},
    action:{},
    getters{}
}

const store=new Vuex.store({
    modules:{
        countAbout,
        personAbout
    }
})

开启命名空间后,组件中读取state数据

//方法一,自己直接读取
this.$sstre.state.personAbout.list
//方法二,借助mapState读取
...mapState('countAbout',['sum','name','hobby'])

组件中读取getters数据

//方法一,自己直接读取
this.$store.getters['personAbout/fistPersonName']
//方法二,借助mapGetter读取
...mapGetters('countAbout',['bigSum'])

开启命名空间后,组件中调用dispatch

//自己直接dispath
this.$store.dispath('personAbout/addPersonWang',person)
//借助mapAction
...mapAction('coutnAbout',{incrementOdd:'jiaOdd',incrementWait:'jiaWait'})

开启命名空间后,组件中调用commit

//自己调用
this.$store.commit('personAbout/add_person',person)
//借助mapMutation
...mapMutation('countAbout',{increment:'JIA'})

  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值