欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 资讯 > vue3定义组件

vue3定义组件

2025/2/3 6:02:36 来源:https://blog.csdn.net/daoshen1314/article/details/142818920  浏览:    关键词:vue3定义组件

在Vue 3中,定义组件有多种方式,包括使用单文件组件(Single File Components, SFC)、使用JavaScript对象定义组件、以及使用组合式API(Composition API)。

1. 单文件组件(SFC)

这是Vue最常见的组件定义方式,使用.vue文件。

示例:MyComponent.vue
<template><div><h1>{{ title }}</h1><button @click="increment">Click me</button><p>Count: {{ count }}</p></div>
</template><script>
export default {name: 'MyComponent',data() {return {title: 'Hello, Vue 3!',count: 0};},methods: {increment() {this.count++;}}
};
</script><style scoped>
h1 {color: blue;
}
</style>
使用组件
<template><div id="app"><MyComponent /></div>
</template><script>
import MyComponent from './components/MyComponent.vue';export default {name: 'App',components: {MyComponent}
};
</script>

2. 使用JavaScript对象定义组件

你可以直接在JavaScript文件中定义组件。

示例:MyComponent.js
export default {name: 'MyComponent',template: `<div><h1>{{ title }}</h1><button @click="increment">Click me</button><p>Count: {{ count }}</p></div>`,data() {return {title: 'Hello, Vue 3!',count: 0};},methods: {increment() {this.count++;}}
};
使用组件
<template><div id="app"><MyComponent /></div>
</template><script>
import MyComponent from './components/MyComponent.js';export default {name: 'App',components: {MyComponent}
};
</script>

3. 使用组合式API(Composition API)

Vue 3引入了组合式API,使得组件逻辑更加灵活和可重用。

示例:MyComponent.vue
<template><div><h1>{{ title }}</h1><button @click="increment">Click me</button><p>Count: {{ count }}</p></div>
</template><script>
import { ref } from 'vue';export default {name: 'MyComponent',setup() {const title = ref('Hello, Vue 3!');const count = ref(0);const increment = () => {count.value++;};return {title,count,increment};}
};
</script><style scoped>
h1 {color: blue;
}
</style>
使用组件
<template><div id="app"><MyComponent /></div>
</template><script>
import MyComponent from './components/MyComponent.vue';export default {name: 'App',components: {MyComponent}
};
</script>

4. 全局注册组件

你也可以全局注册组件,这样就不需要在每个使用的地方单独引入。

示例:main.js
import { createApp } from 'vue';
import App from './App.vue';
import MyComponent from './components/MyComponent.vue';const app = createApp(App);app.component('MyComponent', MyComponent);app.mount('#app');
使用组件
<template><div id="app"><MyComponent /></div>
</template><script>
export default {name: 'App'
};
</script>

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com