0

I' using laravel with vue. In assets folder I created bra.js file with variable.

var name="John"

Then in main.js I added bra.js

require('./bra');

I want to use var name in component.vue like below but I can't.

 <template>
 <div>
 <p> {{ name }}</p>
 </div>
 </template>

Please help.

2
  • you could try global variable window.name = "John", something like that, and use the same in vue component Commented Dec 7, 2019 at 21:53
  • require is a common module, you have to export a variable, then import const bra = require('./bra') Commented Dec 7, 2019 at 21:53

2 Answers 2

1

Variable visibility in the template:

<template>
  <span>{{ variableVisibleInTemplate }}</span>
</template>

<script>
export default {
  data() {
    return {
      variableVisibleInTemplate: variableVisibleInScript
    };
  }
};
</script>

Example 1:

You return exactly one variable

src/assets/bra.js

var name = "John";

module.exports = name;

src/App.vue

<template>
  <span>{{ name }}</span>
</template>

<script>
import name from "./assets/bra.js";
// or:
// const name = require("./assets/bra.js");

export default {
  data() {
    return {
      name: name
    };
  }
};
</script>

Example 2

You return many variables

src/assets/bra.js

var name = "John";

module.exports = {
  name: name
};

src/App.vue

<template>
  <span>{{ name }}</span>
</template>

<script>
import { name } from "./assets/bra.js";
// or:
// const { name } = require("./assets/bra.js");

export default {
  data() {
    return {
      name: name
    };
  }
};
</script>

Read also: Understanding module.exports and exports in Node.js

Sign up to request clarification or add additional context in comments.

Comments

0

Simply use import/export directives.

src/assets/bra.js

export const name = "John";

src/component.vue

<script>
import { name } from "@/assets/bra";

export default {
  ...
  data() {
    return {
      name: name
    }
  }
  ...
};
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.