Vue:检测何时安装新组件
Vue: Detect when new component is mounted
我正在开发撤消功能,在用户单击 'delete' 按钮(类似于 gmail)后,屏幕底部会弹出一个模式。现在,我想在安装撤消组件时禁用 'delete button'。撤消组件和显示它的组件无关,因此我无法 $emit
事件并希望避免使用事件总线。我知道 this.$options.components
包含有关已安装组件的信息 - 所以我基本上是在寻找 watch
更改 $options.components
的方法
非常感谢任何帮助!
观察子组件的内部属性并不是真正的 Vue 方式,像 $options
这样的属性被插件和类似的东西使用,但你不应该在你的日常代码中真正使用它。
理想情况下,您应该有一个 v-if 或一个链接两者的事件,但看起来这是不可能的。
因此,您应该与 Vuex 共享状态,并根据此共享状态进行有条件的行为。类似于:
// store.js
export default new Vuex.Store({
state: {
userCanUndo: false,
},
mutations: {
setUserCanUndo(state, value) {
state.userCanUndo = value;
}
},
}
// Undo.vue
<template>
<div v-if="userCanUndo">
<!-- ... -->
</div>
</template>
<script>
import { mapState } from 'vuex';
export default {
computed: {
...mapState(['userCanUndo']),
},
}
</script>
// DeleteButton.vue
<template>
<button :disabled="userCanUndo" @click="delete">
Delete
</button>
</template>
<script>
import { mapMutations, mapState } from 'vuex';
export default {
computed: {
...mapState(['userCanUndo']),
},
methods: {
...mapMutations(['setUserCanUndo']),
delete() {
// your delete code here
this.setUserCanUndo(true);
setTimeout(() => { this.setUserCanUndo(false); }, 2000);
}
}
我正在开发撤消功能,在用户单击 'delete' 按钮(类似于 gmail)后,屏幕底部会弹出一个模式。现在,我想在安装撤消组件时禁用 'delete button'。撤消组件和显示它的组件无关,因此我无法 $emit
事件并希望避免使用事件总线。我知道 this.$options.components
包含有关已安装组件的信息 - 所以我基本上是在寻找 watch
更改 $options.components
的方法
非常感谢任何帮助!
观察子组件的内部属性并不是真正的 Vue 方式,像 $options
这样的属性被插件和类似的东西使用,但你不应该在你的日常代码中真正使用它。
理想情况下,您应该有一个 v-if 或一个链接两者的事件,但看起来这是不可能的。
因此,您应该与 Vuex 共享状态,并根据此共享状态进行有条件的行为。类似于:
// store.js
export default new Vuex.Store({
state: {
userCanUndo: false,
},
mutations: {
setUserCanUndo(state, value) {
state.userCanUndo = value;
}
},
}
// Undo.vue
<template>
<div v-if="userCanUndo">
<!-- ... -->
</div>
</template>
<script>
import { mapState } from 'vuex';
export default {
computed: {
...mapState(['userCanUndo']),
},
}
</script>
// DeleteButton.vue
<template>
<button :disabled="userCanUndo" @click="delete">
Delete
</button>
</template>
<script>
import { mapMutations, mapState } from 'vuex';
export default {
computed: {
...mapState(['userCanUndo']),
},
methods: {
...mapMutations(['setUserCanUndo']),
delete() {
// your delete code here
this.setUserCanUndo(true);
setTimeout(() => { this.setUserCanUndo(false); }, 2000);
}
}