I would like to know best practices to auto import components inside another component in vue 3.
Auto Import all components from src/components directory that start with "Base" e.g. BaseInput.vue, BaseSelect.vue etc. (Project Created Using Vue CLI)
src/views/EventCreate.vue
<template>
//template data here
</template>
<script>
import upperFirst from "lodash/upperFirst";
import camelCase from "lodash/camelCase";
//require.context function from webpack
const requireComponents = require.context(
"../components",
false,
/Base[A-Z]\w+\.(vue|js)$/
);
let comps = {};
requireComponents.keys().forEach((fileName) => {
//removing extension converting to valid component name e.g. "./base-input.vue" to "BaseInput"
const componentConfig = requireComponents(fileName);
const componentName = upperFirst(
camelCase(fileName.replace(/^\.\/(.*)\.\w+$/, "$1"))
);
//add it to comps object with dynamic name
comps[componentName] = componentConfig.default || componentConfig;
});
export default{
components:{ ...comps }
//remaining exports here
}
</script>
<style scoped>
//style here
</style>
Related
export const ParentCompent = {
template: `
<div >Parent Component</div>
`
}
export const ChildCompent = {
template: `
<div >child Component</div>
`
}
How to import ChildComponent into the ParentCompent when both components are defined in the same Javascript file?
As you said, they are in the same file so there is no need (or way) for import. Imports are only used when you need to import something from different module (file)
Just use local registration
export const ChildCompent = {
template: `<div>child Component</div>`
}
export const ParentCompent = {
components: {
ChildCompent
},
template: `<div><div>Parent Component</div><ChildCompent></ChildCompent></div>`
}
I'm using TreeSelect from Sakai PrimeVUE template, I would like to keep all items expanded on open the component, but could not find this option in the documentation.
My TreeSelect implementation:
<TreeSelect v-model="product.category" :overlayVisible="true" selectionMode="single" :options="categories" #change="categoryChange(product)"></TreeSelect>
Info from my package.json:
"primevue": "^3.11.0",
"vue": "3.2.9",
TreeSelect has a method named expandPath(path), where path is the key property in a tree node.
To expand all nodes, collect all the keys from the tree nodes, and then pass each of them to expandPath():
Add a template ref on <TreeSelect> to use it later in script:
<script setup>
import { ref } from 'vue'
const treeRef = ref()
const treeNodes = ref()
</script>
<template>
<TreeSelect ref="treeRef" :nodes="treeNodes" ⋯ />
</template>
Create a method (e.g., named getKeysFromTree) to extract the keys from an array of tree nodes:
const getKeysFromNode = (node) => {
const keys = [node.key]
if (node.children) {
keys.push(...node.children.flatMap(getKeysFromNode))
}
return keys
}
const getKeysFromTree = (tree) => tree.flatMap(getKeysFromNode)
In an onMounted() hook, use the template ref to call expandPath() on each of the tree's keys (extracted with getKeysFromTree() defined above):
<script setup>
import { onMounted } from 'vue'
onMounted(() => {
const data = /* tree nodes data */
treeNodes.value = data
getKeysFromTree(data).forEach((key) => treeRef.value.expandPath(key))
})
</script>
demo
I'm trying to loop over a list of component described by strings (I get the name of the component from another , like const componentTreeName = ["CompA", "CompA"].
My code is a simple as:
<script setup>
import CompA from './CompA.vue'
import { ref } from 'vue'
// I do NOT want to use [CompA, CompA] because my inputs are strings
const componentTreeName = ["CompA", "CompA"]
</script>
<template>
<h1>Demo</h1>
<template v-for="compName in componentTreeName">
<component :is="compName"></component>
</template>
</template>
Demo here
EDIT
I tried this with not much success.
Use resolveComponent() on the component name to look up the global component by name:
<script setup>
import { resolveComponent, markRaw } from 'vue'
const myGlobalComp = markRaw(resolveComponent('my-global-component'))
</script>
<template>
<component :is="myGlobalComp" />
<template>
demo 1
If you have a mix of locally and globally registered components, you can use a lookup for local components, and fall back to resolveComponent() for globals:
<script setup>
import LocalComponentA from '#/components/LocalComponentA.vue'
import LocalComponentB from '#/components/LocalComponentB.vue'
import { resolveComponent, markRaw } from 'vue'
const localComponents = {
LocalComponentA,
LocalComponentB,
}
const lookupComponent = name => {
const c = localComponents[name] ?? resolveComponent(name)
return markRaw(c)
}
const componentList = [
'GlobalComponentA',
'GlobalComponentB',
'LocalComponentA',
'LocalComponentB',
].map(lookupComponent)
</script>
<template>
<component :is="c" v-for="c in componentList" />
</template>
demo 2
Note: markRaw is used on the component definition because no reactivity is needed on it.
When using script setup, you need to reference the component and not the name or key.
To get it to work, I would use an object where the string can be used as a key to target the component from an object like this:
<script setup>
import CompA from './CompA.vue'
import { ref } from 'vue'
const components = {CompA};
// I do NOT want to use [CompA, CompA] because my inputs are strings
const componentTreeName = ["CompA", "CompA"]
</script>
<template>
<h1>Demo</h1>
<template v-for="compName in componentTreeName">
<component :is="components[compName]"></component>
</template>
</template>
To use a global component, you could assign components by pulling them from the app context. But this would require the app context to be available and the keys known.
example:
import { app } from '../MyApp.js'
const components = {
CompA: app.component('CompA')
}
I haven't tested this, but this might be worth a try to check with getCurrentInstance
import { ref,getCurrentInstance } from 'vue'
const components = getCurrentInstance().appContext.components;
I had tried to use Jest for snapshot testing for Vue SFC. And I missed styles inside the generated snapshot file, only class names. Is it possible to add style rules to snapshot?
<template>
<div class="woof"></div>
</template>
<script>
import Vue from 'vue-class-component';
export default class Component extends Vue {};
</script>
<style lang="scss">
.woof {
background-color: red; // <- this part is missing inside snapshot file
}
</style>
import { shallowMount } from '#vue/test-utils';
import Component from './Component.vue';
describe('Component testing', () => {
it('looks as expected', () => {
const wrapper = shallowMount(Component);
expect(wrapper).toMatchSnapshot();
});
});
I have a Vue 2 project that has many (50+) single-file components. I use Vue-Router for routing and Vuex for state.
There is a file, called helpers.js, that contains a bunch of general-purpose functions, such as capitalizing the first letter of a string. This file looks like this:
export default {
capitalizeFirstLetter(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
}
My main.js file initializes the app:
import Vue from 'vue'
import VueResource from "vue-resource"
import store from "./store"
import Router from "./router"
import App from "./components/App.vue"
Vue.use(VueResource)
const app = new Vue({
router: Router,
store,
template: '<app></app>',
components: { App },
}).$mount('#app')
My App.vue file contains the template:
<template>
<navbar></navbar>
<div class="container">
<router-view></router-view>
</div>
</template>
<script>
export default {
data() {
return {
// stuff
}
}
}
</script>
I then have a bunch of single-file components, which Vue-Router handles navigating to inside the <router-view> tag in the App.vue template.
Now let's say that I need to use the capitalizeFirstLetter() function inside a component that is defined in SomeComponent.vue. In order to do this, I first need to import it:
<template>Some Component</template>
<script>
import {capitalizeFirstLetter} from '../helpers.js'
export default {
data() {
return {
myString = "test"
}
},
created() {
var newString = this.capitalizeFirstLetter(this.myString)
}
}
</script>
This becomes a problem quickly because I end up importing the function into many different components, if not all of them. This seems repetitive and also makes the project harder to maintain. For example if I want to rename helpers.js, or the functions inside it, I then need to go into every single component that imports it and modify the import statement.
Long story short: how do I make the functions inside helpers.js globally available so that I can call them inside any component without having to first import them and then prepend this to the function name? I basically want to be able to do this:
<script>
export default {
data() {
return {
myString = "test"
}
},
created() {
var newString = capitalizeFirstLetter(this.myString)
}
}
</script>
inside any component without having to first import them and then prepend this to the function name
What you described is mixin.
Vue.mixin({
methods: {
capitalizeFirstLetter: str => str.charAt(0).toUpperCase() + str.slice(1);
}
})
This is a global mixin. with this ALL your components will have a capitalizeFirstLetter method, so you can call this.capitalizeFirstLetter(...) from component methods or you can call it directly as capitalizeFirstLetter(...) in component template.
Working example: http://codepen.io/CodinCat/pen/LWRVGQ?editors=1010
See the documentation here: https://v2.vuejs.org/v2/guide/mixins.html
Otherwise, you could try to make your helpers function a plugin:
import Vue from 'vue'
import helpers from './helpers'
const plugin = {
install () {
Vue.helpers = helpers
Vue.prototype.$helpers = helpers
}
}
Vue.use(plugin)
In your helper.js export your functions, this way:
const capFirstLetter = (val) => val.charAt(0).toUpperCase() + val.slice(1);
const img2xUrl = (val) => `${val.replace(/(\.[\w\d_-]+)$/i, '#2x$1')} 2x`;
export default { capFirstLetter, img2xUrl };
or
export default {
capFirstLetter(val) {
return val.charAt(0).toUpperCase() + val.slice(1);
},
img2xUrl(val) {
return `${val.replace(/(\.[\w\d_-]+)$/i, '#2x$1')} 2x`;
},
};
You should then be able to use them anywhere in your components using:
this.$helpers.capitalizeFirstLetter()
or anywhere in your application using:
Vue.helpers.capitalizeFirstLetter()
You can learn more about this in the documentation: https://v2.vuejs.org/v2/guide/plugins.html
Create a new mixin:
"src/mixins/generalMixin.js"
Vue.mixin({
methods: {
capitalizeFirstLetter(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
}
})
Then import it into your main.js like:
import '#/mixins/generalMixin'
From now on you will be able to use the function like this.capitalizeFirstLetter(str) within your component script or without this in a template. i.e.:
<template>
<div>{{ capitalizeFirstLetter('hello') }}</div>
</template>
You have to use this because you mixed a method into the main Vue instance. If there are ways of removing this it will probably involve something unconventional, this at least is a documented way of sharing functions which will be easy to understand for any future Vue devs to your project.
Using Webpack v4
Create a separate file for readability (just dropped mine in plugins folder).
Reproduced from #CodinCat and #digout responses.
//resources/js/plugins/mixin.js
import Vue from 'vue';
Vue.mixin({
methods: {
capitalizeFirstLetter: str => str.charAt(0).toUpperCase() + str.slice(1),
sampleFunction() {
alert('Global Functions');
},
}
});
Then, import in your main.js or app.js file.
//app.js
import mixin from './plugins/mixin';
USAGE:
Call this.sampleFunction() or this.capitalizeFirstLetter().
Use a global filter if it only concerns how data is formatted when rendered. This is the first example in the docs:
{{ message | capitalize }}
Vue.filter('capitalize', function (value) {
if (!value) return ''
value = value.toString()
return value.charAt(0).toUpperCase() + value.slice(1)
})
Great question. In my research I found vue-inject can handle this in the best way. I have many function libraries (services) kept separate from standard vue component logic handling methods. My choice is to have component methods just be delegators that call the service functions.
https://github.com/jackmellis/vue-inject
Import it in the main.js file just like 'store' and you can access it in all the components.
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
store,
router,
render: h => h(App)
})