- Define the component's data property using the
data
function in the Vue component options.
export default Vue.extend({
data() {
return {
myData: "Hello, Vue!",
};
},
});
- Specify the data type for the data property by providing a type annotation.
export default Vue.extend({
data(): { myData: string } {
return {
myData: "Hello, Vue!",
};
},
});
- Access the data property within the component's template.
<template>
<div>
{{ myData }}
</div>
</template>
- Use the data property in methods or computed properties if needed.
export default Vue.extend({
data(): { myData: string } {
return {
myData: "Hello, Vue!",
};
},
methods: {
updateData() {
this.myData = "Updated data!";
},
},
});
- Ensure that the component is correctly imported and registered in the parent component or the main application file.
// Import the component
import MyComponent from "@/components/MyComponent.vue";
// Register the component
export default Vue.extend({
components: {
MyComponent,
},
});
- Include the component in the parent component's template.
<template>
<div>
<my-component></my-component>
</div>
</template>
- Make sure that the Vue instance is properly created and mounted to the target element in the main application file.
import Vue from "vue";
import App from "./App.vue";
new Vue({
render: (h) => h(App),
}).$mount("#app");