这里必要留意的是:因为vuex里,我们生涯的状态,都是数组,而localStorage只支持字符串,以是必要用JSON转换:
- JSON.stringify(state.subscribeList); // array -> string
- JSON.parse(window.localStorage.getItem("subscribeList")); // string -> array
要领四、$attrs/$listeners
1.简介
多级组件嵌套必要转达数据时,凡是行使的要领是通过vuex。但假如仅仅是转达数据,而不做中间处理赏罚,行使 vuex 处理赏罚,未免有点大材小用。为此Vue2.4 版本提供了另一种要领----$attrs/$listeners
- $attrs:包括了父浸染域中不被 prop 所辨认 (且获取) 的特征绑定 (class 和 style 除外)。当一个组件没有声明任何 prop 时,这里会包括全部父浸染域的绑定 (class 和 style 除外),而且可以通过 v-bind="$attrs" 传入内部组件。凡是共同 interitAttrs 选项一路行使。
- $listeners:包括了父浸染域中的 (不含 .native 修饰器的) v-on 变乱监听器。它可以通过 v-on="$listeners" 传入内部组件
接下来我们看个跨级通讯的例子:
- // index.vue
- <template>
- <div>
- <h2>浪里行舟</h2>
- <child-com1
- :foo="foo"
- :boo="boo"
- :coo="coo"
- :doo="doo"
- title="前端工匠"
- ></child-com1>
- </div>
- </template>
- <script>
- const childCom1 = () => import("./childCom1.vue");
- export default {
- components: { childCom1 },
- data() {
- return {
- foo: "Javascript",
- boo: "Html",
- coo: "CSS",
- doo: "Vue"
- };
- }
- };
- </script>
- // childCom1.vue
- <template class="border">
- <div>
- <p>foo: {{ foo }}</p>
- <p>childCom1的$attrs: {{ $attrs }}</p>
- <child-com2 v-bind="$attrs"></child-com2>
- </div>
- </template>
- <script>
- const childCom2 = () => import("./childCom2.vue");
- export default {
- components: {
- childCom2
- },
- inheritAttrs: false, // 可以封锁自动挂载到组件根元素上的没有在props声明的属性
- props: {
- foo: String // foo作为props属性绑定
- },
- created() {
- console.log(this.$attrs); // { "boo": "Html", "coo": "CSS", "doo": "Vue", "title": "前端工匠" }
- }
- };
- </script>
- // childCom2.vue
- <template>
- <div class="border">
- <p>boo: {{ boo }}</p>
- <p>childCom2: {{ $attrs }}</p>
- <child-com3 v-bind="$attrs"></child-com3>
- </div>
- </template>
- <script>
- const childCom3 = () => import("./childCom3.vue");
- export default {
- components: {
- childCom3
- },
- inheritAttrs: false,
- props: {
- boo: String
- },
- created() {
- console.log(this.$attrs); // { "boo": "Html", "coo": "CSS", "doo": "Vue", "title": "前端工匠" }
- }
- };
- </script>
- // childCom3.vue
- <template>
- <div class="border">
- <p>childCom3: {{ $attrs }}</p>
- </div>
- </template>
- <script>
- export default {
- props: {
- coo: String,
- title: String
- }
- };
- </script>

如上图所示$attrs暗示没有担任数据的工具,名目为{属性名:属性值}。Vue2.4提供了$attrs , $listeners 来转达数据与变乱,跨级组件之间的通信变得更简朴。
简朴来说:$attrs与$listeners 是两个工具,$attrs 里存放的是父组件中绑定的非 Props 属性,$listeners里存放的是父组件中绑定的非原闹变乱。
要领五、provide/inject
1.简介 (编辑:湖南网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|