在 Vue 3.0 中,选项(Options)和资源(Resources)是指组件配置和相关资源的一些设置。让我们来看一下 Vue 3.0 中与选项和资源相关的一些内容:

1. 选项

1.1. components 选项

在 Vue 3.0 中,你可以使用 components 选项来注册局部组件。
<script>
import MyComponent from './MyComponent.vue';

export default {
  components: {
    'my-component': MyComponent,
  },
};
</script>

1.2. directives 选项

使用 directives 选项来注册局部指令。
<script>
import MyDirective from './MyDirective';

export default {
  directives: {
    'my-directive': MyDirective,
  },
};
</script>

2. 资源

2.1. watch 选项

在 Vue 3.0 中,watch 选项也可以用于监听数据的变化。不同于 Vue 2.x,你可以直接在 setup 函数中使用 watch 函数。
<script>
import { ref, watch } from 'vue';

export default {
  setup() {
    const count = ref(0);

    watch(count, (newValue, oldValue) => {
      console.log(`count changed from ${oldValue} to ${newValue}`);
    });

    return {
      count,
    };
  },
};
</script>

2.2. provide 和 inject 选项

在 Vue 3.0 中,使用 provide 和 inject 选项来实现祖先向后代组件传递数据。
<script>
import { provide, ref, inject } from 'vue';

const sharedDataKey = Symbol();

export default {
  setup() {
    const sharedData = ref('Shared data');

    provide(sharedDataKey, sharedData);

    return {
      sharedData,
    };
  },
};

// In child component
<script>
import { inject } from 'vue';

const sharedDataKey = Symbol();

export default {
  setup() {
    const sharedData = inject(sharedDataKey);

    return {
      sharedData,
    };
  },
};
</script>

注意事项:

  •  在 Vue 3.0 中,选项和资源的使用方式基本保持一致,但是在使用 watch 和 provide / inject 时,需要在 setup 函数中使用对应的函数。

  •  Vue 3.0 引入了 Composition API,使得组件的逻辑更加灵活和易于理解。在新的组件中,推荐使用 Composition API 的方式来组织组件逻辑,而不仅仅是依赖于选项的设置。

  
以上是 Vue 3.0 中选项和资源的一些常见用法,具体的使用方式取决于你的应用需求和组织结构。


转载请注明出处:http://www.pingtaimeng.com/article/detail/570/Vue 3.0