Nuxt, VueJS This must be called within a setup function - vue.js

I've got a project. It's currently available on a certain website. I need to implement some changes. When I download a project from gitlab and run it throws me an error:This must be called within a setup function.
path: .nuxt/composition-api/index.js
const useContext = () => {
const vm = CompositionApi.getCurrentInstance();
if (!vm)
throw new Error("This must be called within a setup function.");
return {
...(vm[globalNuxt] || vm.$options).context,
route: CompositionApi.computed(() => vm.$route),
query: CompositionApi.computed(() => vm.$route.query),
What is wrong?
I need to run the project to make some changes but can't deploy it on my local server.
Update:
useContex is in default.vue
...
setup (_, { isServer, refs }: any) {
// console.info(context)
// const refs = context.refs
const { store } = useContext()
const { scrolllock } = scrollLock(store)
const locationName = computed(() => store.getters.locationName)
const location = computed({
set (val: boolean) {
store.dispatch('setLocationModal', val)
},
get () {
return store.getters.locationModal
}
})
...
cmd output when I'm trying to go the site
[Vue warn]: [vue-composition-api] already installed. Vue.use(VueCompositionAPI) should be called only once.
ERROR [Vue warn]: Error in data(): "Error: This must be called within a setup function." 22:50:04
found in
---> <Layouts/default.vue> at layouts/default.vue
<Root>
ERROR [Vue warn]: Error in data(): "Error: This must be called within a setup function." 22:50:05
found in
---> <Layouts/default.vue> at layouts/default.vue
<Root>
ERROR [Vue warn]: Error in data(): "Error: This must be called within a setup function." 22:50:24
found in
---> <Layouts/default.vue> at layouts/default.vue
<Root>

From my experience, npm can't install #nuxtjs/composition-api older versions, or stuff like that, so I did uninstall its older version and install the new version and it's worked
here is what I've done
rm -rf node_modules && rm -rf package-lock.json && npm uninstall #nuxtjs/composition-api && npm i #nuxtjs/composition-api && npm i

From the look of things, it seems you
You created another plugin for the VueCompositionAPI when it is installed already e.g #nuxtjs/composition-api
I would advise you to remove any other composition-api from your project and stick to the latest version of the official #nuxtjs/composition-api with Vuex v4 for Nuxt 2
In the latest version of #nuxtjs/composition-api, you could use
const store = useStore();
// OR
const { store } = useContext();
NOTE: You have to define the helper functions like const router = useStore() directly inside your setup() function, and not inside your method, to avoid This must be called within a setup function error.
For those that want to use route
To smooth your upgrade to Nuxt 3, it is recommended not to access route, query, from and params from useContext but rather to use the useRoute helper function.

I don't know what happened there. I deleted that repository and cloned it again.
Next up I did this:
npm init
and then
npm run dev
And it works.

Related

How do you resolve the 500 error "Navigator is not defined" when installing third-party plugins in a Nuxt 3 app?

I am currently unable to use third-party plugins in my Nuxt 3 application. Here's what my code/setup looks like:
In my package.json I have the following dependency: "#braze/web-sdk": "^4.6.1"
In my plugins/ directory, I have a braze.client.js file
Within the braze.client.js file, I have the following:
import * as braze from '#braze/web-sdk'
export default defineNuxtPlugin(() => {
braze.initialize(apiKey, {
baseUrl: apiEndpoint
})
return {
provide: {
openSession
}
}
})
Within my nuxt.config.ts, I added the following (since my project has Vite, I followed Braze's documentation here: https://www.braze.com/docs/developer_guide/platform_integration_guides/web/initial_sdk_setup/#vite):
optimizeDeps: {
exclude: ['#braze/web-sdk']
}
Then within my <script> tags within the page/component, I have the following:
const { $openSession } = useNuxtApp()
onMounted(() => {
$openSession()
})
All the steps above continue to create a "500 navigator is not defined" error and I'm stumped with how I can resolve it.
I tried using beforeOnMount, not using as lifecycle hook, as well as placing $openSession() within an if statement:
if (process.client) {
}
Yet no matter what, it still renders the 500 error.

How to prerender a Vue3 application?

I try without success to apply a prerendering (or a SSG) to my Vue3 application to make it more SEO friendly.
I found the vue-cli-plugin-prerender-spa, and when I try it with the command line: vue add prerender-spa I have the error:
ERROR TypeError: Cannot read properties of undefined (reading 'endsWith')
After that I tried prerender-spa-plugin but I have an error when I make a npm run build:
[prerender-spa-plugin] Unable to prerender all routes!
ERROR Error: Build failed with errors.
Error: Build failed with errors.
at /Users/myusername/Workspace/myproject/node_modules/#vue/cli-service/lib/commands/build/index.js:207:23
at /Users/myusername/Workspace/myproject/node_modules/webpack/lib/webpack.js:148:8
at /Users/myusername/Workspace/myproject/node_modules/webpack/lib/HookWebpackError.js:68:3
What do you think about this? Do you have any idea?
Nuxt3 is a really powerful meta-framework with a lot of features and huge ecosystem. Meanwhile, it's in RC2 right now so not 100% stable (may still work perfectly fine).
If your project is aiming for something simpler, I'd recommend using Vitesse. It may be a bit more stable and it's probably powerful enough (check what's coming with it to help you decide).
Some solutions like Prerender also exist but it's paid and not as good as some real SSG (/SSR). Also, it's more of a freemium.
I struggled with the same error output until I found the prerender-spa-plugin-next. Then I notice the latest version of prerender-spa-plugin was published 4 years ago and prerender-spa-plugin-next is continually updating. It seems like that prerender-spa-plugin-next is a new version of prerender-spa-plugin with the same functions. So I use prerender-spa-plugin-next instead of prerender-spa-plugin then everything works fine!
Here is my step:
install the package
npm i -D prerender-spa-plugin-next
modify vue.config.js like
const plugins = [];
if (process.env.NODE_ENV === 'production') {
const { join } = require('path');
const PrerenderPlugin = require('prerender-spa-plugin-next');
plugins.unshift(
new PrerenderPlugin({
staticDir: join(__dirname, 'dist'),
routes: ['/'], //the page route you want to prerender
})
);
}
module.exports = {
transpileDependencies: true,
configureWebpack(config) {
config.plugins = [...config.plugins, ...plugins];
},
};
build
npm run build
Then check the index.html under the dist folder you can see the page is prerendered.
Further usage refers to the homepage of prerender-spa-plugin-next
Found and fix about the scss files to import.
In nuxt.config.ts use :
vite: {
css: {
preprocessorOptions: {
scss: {
additionalData: `
#import "#/assets/scss/_variables.scss";
#import "#/assets/scss/my-style.scss";
`
}
},
},
}
Now my 2 mains issue are : how to install vuetify properly, currently syles and components seems working but the JS not, for example, accordions don't expands on click.
And second topic is to have a i18n module, it seems that vue-i18N no longer works.
Thanks.

Runtime Error integrating a component lib that uses #vue/composition-api: 'You must use this function within the "setup()" method'

Any help with the following problem would be greatly appreciated!
Situation:
My project contains two packages:
child-component-lib
contains a single view About.vue written in composition-API-style (with vue2 helper libraries #vue/composition-api and vuex-composition-helpers)
exports a single RouteConfig
build as a lib
views/About.vue (child)
<template>
<div class="about">
<h1>This is an about page (as component lib)</h1>
</div>
</template>
<script>
import { defineComponent } from "#vue/composition-api";
import { createNamespacedHelpers } from "vuex-composition-helpers";
export default defineComponent({
components: {},
setup(_, { root }) {
const { useGetters, useActions } = createNamespacedHelpers("account"); // error thrown here!
}
});
</script>
router/index.ts (child)
export const routes: Array<RouteConfig> = [{
path: "/",
name: "About",
component: () => import(/* webpackChunkName: "about" */ "../views/About.vue")
}];
lib.ts (child)
export const routes = require("#/router").routes;
package.json (child)
"scripts": {
"build": "vue-cli-service build --target lib --name child-component-lib src/lib.ts"
...
parent-app
imports the route from child-component-lib into its router
contains a simple view that displays one line of text and a <router-view />
package.json (parent)
"dependencies": {
"#tholst/child-component-lib": "file:../child-component-lib",
router/index.ts (parent)
import { routes as childComponentRoutes } from "#tholst/child-component-lib";
const routes: Array<RouteConfig> = [...childComponentRoutes];
const router = new VueRouter({routes});
export default router;
App.vue (parent)
<template>
<div id="app">
<Home />
<router-view />
</div>
</template>
<script>
import { defineComponent } from "#vue/composition-api";
import Home from "#/views/Home.vue";
export default defineComponent({
components: {
Home
},
setup(_, { root }) {
...
}
});
</script>
Expected behavior
It works without problems.
Actual behavior
I see an error output in the console. [Vue warn]: Error in data(): "Error: You must use this function within the "setup()" method, or insert the store as first argument." The error message is misleading, because the error is actually thrown inside setup() method. It can be traced back to getCurrentInstance() returning undefined (inside #vue/composition-api).
Investigation:
It turns out that the error disappears when I include the same About.vue in the parent-app itself (just switch the route, to try it out), i.e., it works when we avoid the import from the built library.
So it looks like it's a problem with the build setup
(one of vue.config.js, webpack, babel, typescript, ...)
Reproduce the error:
1. Clone, install, run
git clone git#github.com:tholst/vue-composition-api-comp-lib.git && cd vue-composition-api-comp-lib/child-component-lib && npm install && npm run build && cd ../parent-app/ && npm install && npm run serve
or one by one
git clone git#github.com:tholst/vue-composition-api-comp-lib.git
cd vue-composition-api-comp-lib/child-component-lib
npm install
npm run build
cd ../parent-app/
npm install
npm run serve
2. Open Browser
Go to http://localhost:8080/
3. Open Dev Tools to See Error
[Vue warn]: Error in data(): "Error: You must use this function within the "setup()" method, or insert the store as first argument."
found in
---> <Anonymous>
<App> at src/App.vue
<Root>
Error Screenshot
Environment Info:
Node: 14.2.0
npm: 6.14.8
Chrome: 86.0.4240.198
npmPackages:
#vue/babel-sugar-composition-api-inject-h: 1.2.1
#vue/babel-sugar-composition-api-render-instance: 1.2.4
...
#vue/cli-overlay: 4.5.8
#vue/cli-plugin-babel: 4.5.8
#vue/cli-plugin-router: 4.5.8
#vue/cli-plugin-typescript: 4.5.8
#vue/cli-plugin-vuex:4.5.8
#vue/cli-service: 4.5.8
#vue/cli-shared-utils: 4.5.8
#vue/component-compiler-utils: 3.2.0
#vue/composition-api: 1.0.0-beta.19
#vue/preload-webpack-plugin: 1.1.2
typescript: 3.9.7
vue: 2.6.12
vue-loader: 15.9.5 (16.0.0-rc.1)
vue-router: 3.4.9
vue-template-compiler: 2.6.12
vue-template-es2015-compiler: 1.9.1
vuex: 3.5.1
vuex-composition-helpers: 1.0.21
npmGlobalPackages:
#vue/cli: 4.5.8
I finally understood what the problems were. First, there was the actual problem. Second, there was a problem in the local development setup that made solutions to the actual problem look like they were not working.
The Actual Problem + Solution
The child-component-lib was bundling their own versions of the npm packages #vue/composition-api and vuex-composition-helpers. This had the following effect: When I was running the parent-app there were actually two instances of those libraries and the vue component from the child-component-lib was accessing the wrong object that had not been properly initialized.
The solution was to prevent the bundling of those libraries in the child-component-lib, by
making them devDependencies and peerDependencies.
instructing webpack not to bundle them on npm run build.
package.json
"dependencies": {
...
},
"devDependencies": {
"#vue/composition-api": "^1.0.0-beta.19",
"vuex-composition-helpers": "^1.0.21",
...
},
"peerDependencies": {
"#vue/composition-api": "^1.0.0-beta.19",
"vuex-composition-helpers": "^1.0.21"
},
vue.config.js
configureWebpack: {
externals: {
"#vue/composition-api": "#vue/composition-api",
"vuex-composition-helpers": "vuex-composition-helpers"
},
...
}
The Tricky Problem that Made Things Difficult
I was trying to fix this problem locally, without actually publishing the package. And it seemed to work, because I was seeing the same problem locally that I also saw in the published packages.
I did local development by directly linking the parent-app and child-component-libs. I tried both
a direct folder dependency
package.json
"dependencies": {
"#tholst/child-component-lib": "file:../child-component-lib",
},
npm link
cd child-component-lib
npm link
cd ../parent-app
npm link #tholst/child-component-lib
Both approaches have the effect that they actually import (=symlink to) the child-component-lib's folder with all files and folders (instead of only the files that would be published in the npm package).
And that meant the following: Even though I had excluded the two composition-API libs from the bundle and made them dev/peer dependencies (see solution to actual problem), they were still installed and present in the child-component-lib's node_modules. And that node_modules folder was symlinked into the parent-app package. And in this way the child-component-lib still had access to their own copy of the libraries that we wanted to exclude from the build (see actual problem). And I was still seeing the error as before.
And this way my local development approach obscured the fact that the solution to the actual problem was actually working.

React Native MQTT Module `url` does not exist in the Haste module map

I want to explore this project https://github.com/mqttjs/MQTT.js within the React Native environment. So I did this:
react-native init myproject
npm install --save mqtt
Then I pasted this sample code from the mqttjs into my App.js a bit after the "Welcome to React Native" component.
var mqtt = require('mqtt')
var client = mqtt.connect('mqtt://test.mosquitto.org')
client.on('connect', function () {
client.subscribe('presence', function (err) {
if (!err) {
client.publish('presence', 'Hello mqtt')
}
})
})
client.on('message', function (topic, message) {
// message is Buffer
console.log(message.toString())
client.end()
})
But when I run react-native run-android, I get a compilation error with a message like
Module url does not exist in the Haste module map
I tried replacing mqtt://test.mosquitto.org with a url to my own mosquitto broker with some of these values: mqtt://192.168.0.20, tcp://192.168.0.20, 192.168.0.20. But all these still generated the same error.
What am I doing wrong?
You can solve this by explicitly installing the url module:
npm install url

VueJS use NPM Component in Browser using Browserify

I have a custom component in my page, defined as:
Vue.component('payment-page', {
template: '#payment-template',
data: function () {
return {
...
}
},
components: {
DatePicker
},
});
Now, in this component, I need to use a datepicker/daterange picker, of which I found this to be most helpful. It can be installed from NPM using npm install vue2-datepicker --save. I am using browserify so as to be able to use the datepicker in the browser, inside my component above.
For browserify, inside my main.js file I have this:
let DatePicker = require('vue2-datepicker');
then I use the command browserify main.js -o bundle.js to create my bundle.js file which I then import in my HTML file.
Problem is I always get the error Uncaught ReferenceError: DatePicker is not defined. Anything I'm doing wrong?