在模板和代码中访问 vue3 深层对象时,它们的名称更短

问题描述 投票:0回答:1

如何绕过对象的长名称,例如

buttons.btnCancel.inactive
?我尝试过使用
const {btnCancelInactive: inactive, btnCancelInactiveClass: inactiveClass, btnCancelActiveClass: activeClass} = buttons.btnCancel
进行简单的解构,但我失去了反应性。我尝试解构 toRefs 但甚至值 btnCancelInactive 也是空的。

完整代码如下:

//vueAddItemPanel.js

const template = `
    <div class="input-group input-group-sm">
      <input 
       type="text"
       class="form-control" 
       placeholder="Select a role to add..."
       ref="searchInputRef"
       v-model="searchText"
       >
      <button 
       class="btn disabled text-muted" 
       type="button">
       <i class="fas fa-check"></i></button>
      <button 
       :class="[btnCancelInactive ? btnCancelInactiveClass : btnCancelActiveClass]"
       type="button"
       @click.stop="clearSearch">
       <i class="fas fa-x"></i></button>
    </div>
    sss {{btnCancelInactive}}
`

const {ref, reactive, watch, toRefs, } = Vue;

const vueAddItemPanel = {
    setup(props, ctx) {
        const searchText = ref('')
        const searchInputRef = ref(null)
        const buttons = reactive({
            btnCancel : {
                inactive : true,
                inactiveClass : "btn btn-outline-secondary disabled text-muted",
                activeClass : "btn btn-outline-secondary"
            }
        })

        const {btnCancelInactive, btnCancelInactiveClass, btnCancelActiveClass 
            } = toRefs( buttons.btnCancel )

        // note: debounce is from lodash
        const debouncedSearch = _.debounce(() => {
            ctx.emit('searchChanged', searchText.value)
        }, 500)
        
        watch( searchText, () => {
            buttons.btnCancel.inactive = searchText.value.trim() === ''
            debouncedSearch()        
        })

        const clearSearch = () => {
            searchText.value = ''
            searchInputRef.value.focus()
            buttons.btnCancel.inactive = true
        }

        return {
            searchText, clearSearch, debouncedSearch, searchInputRef,
            btnCancelInactive, btnCancelInactiveClass, btnCancelActiveClass,
        }
    },
    template: template,
}

export default vueAddItemPanel
vue.js vuejs3 vue-component
1个回答
0
投票

为了避免失去反应性并使模板中的访问更容易,请使用计算属性

    // Computed properties for easier access in templates
    const isBtnCancelInactive = computed(() => buttons.btnCancel.inactive);
    const inactiveClass = computed(() => buttons.btnCancel.inactiveClass);
    const activeClass = computed(() => buttons.btnCancel.activeClass);

© www.soinside.com 2019 - 2024. All rights reserved.