NIUCLOUD是一款SaaS管理后台框架多应用插件+云编译。上千名开发者、服务商正在积极拥抱开发者生态。欢迎开发者们免费入驻。一起助力发展! 广告
[TOC] ## 方法一 ### 1. 组件中定义事件将参数传给vuex ~~~ <li @click="handleclick" v-for="(item,index) of cities" :key="index">{{index}}</li> <script> export default { name:"CityWord", props:['cities'], methods:{ handleclick(event){ //将参数传递给store.js中的actions:方法中 this.$store.dispatch("changeLetter",event.target.innerText) } } } </script> ~~~ ### 2. 在store.js中的actions:方法中接收 ~~~ //接收子组件传递的事件 将改变的值传给mutations actions: { //函数名为传递过来的函数名 参数 ctx为上下文 letter为传递的值 changeLetter(ctx,letter){ // console.log(letter); // 通过commit传递给 mutations: ctx.commit("changeLetter",letter) } ~~~ ### 3. mutations:中接收 ~~~ mutations: { //函数名为传递过来的函数名 参数 代表state属性 letter为state中的值 changeLetter(state,letter){ state.letter=letter } }, ~~~ ### 4. state中的数据 ~~~ //相当于data state: { letter:"" }, ~~~ ### 5. 再页面或组件中使用state中的值 ~~~ <!-- 使用vuex中的数据 --> {{this.$store.state.letter}} ~~~ ### 6. 用接收到的值通过监听和计算属性实现相应功能 ~~~ <div class="area" v-for="(item,index) of cities" :key="item.id" :ref="index"> <p class="title">{{index}}</p> <div class="list-city" v-for="(city,inx) of item" :key="inx">{{city.name}}</div> </div> ~~~ ~~~ //通过计算属性接收到子组件(word)传递给vuex然后传过来的参数letter computed: { //通过定义参数的函数来获取到参数 letter(){ return this.$store.state.letter } }, watch:{ //通过定义参数的监听函数监听参数的改变从而改变html中设置 :ref="index"属性的值 //:ref="index"为页面所跳转的位置里面传的参数为for循环的对象中的属性名相当于数组中的下标因为循环的是个对象 letter(){ //console.log(1) console.log(this.$refs) //控制页面跳转到本页面中的指定位置 const element = this.$refs[this.letter][0]; this.scroll.scrollToElement(element); } } ~~~ ## 方法二 ~~~ 基本同方法一: ①将步骤一种的 this.$store.dispatch 改为 this.$store.commit ②去掉步骤二 ~~~