link1507 link1508 link1509 link1510 link1511 link1512 link1513 link1514 link1515 link1516 link1517 link1518 link1519 link1520 link1521 link1522 link1523 link1524 link1525 link1526 link1527 link1528 link1529 link1530 link1531 link1532 link1533 link1534 link1535 link1536 link1537 link1538 link1539 link1540 link1541 link1542 link1543 link1544 link1545 link1546 link1547 link1548 link1549 link1550 link1551 link1552 link1553 link1554 link1555 link1556 link1557 link1558 link1559 link1560 link1561 link1562 link1563 link1564 link1565 link1566 link1567 link1568 link1569 link1570 link1571 link1572 link1573 link1574 link1575 link1576 link1577 link1578 link1579 link1580 link1581 link1582 link1583 link1584 link1585 link1586 link1587 link1588 link1589 link1590 link1591 link1592 link1593 link1594 link1595 link1596 link1597 link1598 link1599 link1600 link1601 link1602 link1603 link1604 link1605 link1606 link1607 link1608 link1609 link1610 link1611 link1612 link1613 link1614 link1615 link1616 link1617 link1618 link1619 link1620 link1621 link1622 link1623 link1624 link1625 link1626 link1627 link1628 link1629 link1630 link1631 link1632 link1633 link1634 link1635 link1636 link1637 link1638 link1639 link1640 link1641 link1642 link1643

[Vue.js] Can vue-router open a link in a new tab?

there is a summary page and a detail subpage. All of the routes are implemented with vue-router (v 0.7.x) using programmatic navigation like this:

this.$router.go({ path: “/link/to/page” })

However, when I route from the summary page to the subpage, I need to open the subpage in a new tab just as one would by adding _target=”blank” to an <a> tag.

Is there a way to do this?

Solution :

I think that you can do something like this:

let routeData = this.$router.resolve({name: ‘routeName’, query: {data: “someData”});
window.open(routeData.href, ‘_blank’);

it worked for me.
thanks.

Solution 2:

It seems like this is now possible in newer versions (vue.js Router 3.0.1):

<router-link :to=”{ name: ‘fooRoute’}” target=”_blank”>
Link Text
</router-link>

Solution 3:

For those who are wondering the answer is no.
See related issue on github.

Q: Can vue-router open link in new tab progammaticaly

A: No. use a normal link.

Solution 4:

In case that you define the route like the one asked in the question (path: ‘/link/to/page’):

import vue.js from ‘vue’
import Router from ‘vue-router’
import MyComponent from ‘@/components/MyComponent.vue’;

Vue.use(Router)

export default new Router({
routes: [
{
path: ‘/link/to/page’,
component: MyComponent
}
]
})

You can resolve the URL in the summary page and open the sub page as below:

<script>
export default {
methods: {
popup() {
let route = this.$router.resolve({path: ‘/link/to/page’});
// let route = this.$router.resolve(‘/link/to/page’); // This also works.
window.open(route.href, ‘_blank’);
}
}
};
</script>

Of course if you’ve given the route a name, you can resolve the URL by name:

routes: [
{
path: ‘/link/to/page’,
component: MyComponent,
name: ‘subPage’
}
]

let route = this.$router.resolve({name: ‘subPage’});

References:

vue-router router.resolve(location, current?, append?)
vue-router router-link

Solution 5:

I think the best way is to simply use:

window.open(“yourURL”, ‘_blank’);

* flies away *

[Vue.js] Array shows 0 as length when it has elements in it

So there is an object like so:

this.$ - this holds indexes that hold arrays. For instance, it has two different indexes: one called slide and one called thumb. Those indexes hold arrays.

I’m developing in vue.js and got those to show up with the v-ref attribute. However, whenever I do this:

console.log(this.$.slide.length)

It comes back as 0. I’m trying to loop through it using forEach() but can’t since it shows 0 even though there are clearly 4 VueComponent objects inside that array.

I’m not really understanding why it says slide: array[0], but then shows slide: array[4] on the next line. I tried going in this.$.slide.slide, but that’s undefined.

Thanks for any insight.

EDIT:

This is my HTML for Vue:

<slider inline-template img-count=”4” v-ref=”slider”>
<div class=”slides” v-style=”styles”>
<sliderslide v-repeat=”count” v-ref=”slide”>
<img src=”{ gallery_image(‘HM722_Silver_Creek_9978.jpg’, ‘full’) }” alt=”HM722 Silver Creek” style=”margin-top:-15%;” />
</sliderslide>
</div>

<div class=”thumbnails”>
<div class=”thumbnail-wrapper”>
<sliderthumb v-repeat=”count” send-index=”@{ updateIndex }” v-ref=”thumb”
image-src=”{ gallery_image(‘HM722_Silver_Creek_9978.jpg’) }”
image-alt=””
caption=”Newest Product”>
</sliderthumb>
</div>
</div>
</slider>

The v-refs are already there so it should show them…

I’m console.log() all of this inside the ready method inside Vue.

Solution :

This is a timing issue. The first time you ask for the length it is indeed 0, but when you inspect the object a few seconds later with Chrome Dev Tools you are inspecting the live object which has now been filled.

You can confirm this by using setTimeout

setTimeout(function(){
console.log(this.$.slide.length);
}, 1000)

Sounds like the ready event isn’t working the way you expected.

Update

To solve the problem of setting with photo widths without glitching, you can use setTimeout 0 to defer the execution. JS is single threaded and this will let the rendering finish before setting the width

// `0` will ‘defer’
setTimeout(this.setSlideDimensions.bind(this), 0);
setTimeout(this.setThumbDimensions.bind(this), 0);

Some people frown upon doing this as it can be a sign of bad logic, but without more knowledge of how Vue.js works, I would say this would be the best solution for now.

Updated jsFiddle

[Vue.js] How can I add link in the card deck groups?

I get reference from here : https://bootstrap-vue.js.org/docs/components/card/#card-deck-groups

The script like this :

<div>
<b-card-group deck>
<b-card title=”Title”
img-src=”https://picsum.photos/300/300/?image=41"
img-alt=”Img”
img-top>
<p class=”card-text”>
This is a wider card with supporting text below as a
natural lead-in to additional content. This content
is a little bit longer.
</p>
<div slot=”footer”>
<small class=”text-muted”>Last updated 3 mins ago</small>
</div>
</b-card>
<b-card title=”Title”
img-src=”https://picsum.photos/300/300/?image=41"
img-alt=”Img”
img-top>
<p class=”card-text”>
This card has supporting text below as a natural lead-in
to additional content.
</p>
<div slot=”footer”>
<small class=”text-muted”>Last updated 3 mins ago</small>
</div>
</b-card>
<b-card title=”Title”
img-src=”https://picsum.photos/300/300/?image=41"
img-alt=”Img”
img-top>
<p class=”card-text”>
This is a wider card with supporting text below as a natural
lead-in to additional content. This card has even longer content
than the first to show that equal height action.
</p>
<div slot=”footer”>
<small class=”text-muted”>Last updated 3 mins ago</small>
</div>
</b-card>
</b-card-group>
</div>

to add link in the title and image

How can I do it?

Solution :

You have to remove the title attribute from the b-card and just use a b-link inside a b-card-body instead…

<b-card img-src=”https://picsum.photos/300/300/?image=41"
img-alt=”Img”
img-top
\>
<b-card-body>
<b-link to=”/“>
Title
</b-link>
<p class=”card-text”>
This is a wider card with supporting text below as a
natural lead-in to additional content. This content
is a little bit longer.
</p>
</b-card-body>
</b-card>

[Vue.js] vue.js disable input conditionally

there is an input:

<input type=”text” id=”name” class=”form-control” name=”name” v-model=”form.name” :disabled=”validated ? ‘’ : disabled”>

and in my Vue.js component, I have:

..
..
ready() {
this.form.name = this.store.name;
this.form.validated = this.store.validated;
},
..

validated being a boolean, it can be either 0 or 1, but no matter what value is stored in the database, my input is always disabled.

I need the input to be disabled if false, otherwise it should be enabled and editable.

Update:

Doing this always enables the input (no matter there is 0 or 1 in the database):

<input type=”text” id=”name” class=”form-control” name=”name” v-model=”form.name” :disabled=”validated ? ‘’ : disabled”>

Doing this always disabled the input (no matter there is 0 or 1 in the database):

<input type=”text” id=”name” class=”form-control” name=”name” v-model=”form.name” :disabled=”validated ? disabled : ‘’”>

Solution :

To remove the disabled prop, you should set its value to false. This needs to be the boolean value for false, not the string ‘false’.

So, if the value for validated is either a 1 or a 0, then conditionally set the disabled prop based off that value. E.g.:

<input type=”text” :disabled=”validated == 1”>

Here is an example.

Solution 2:

you could have a computed property that returns a boolean dependent on whatever criteria you need.

<input type=”text” :disabled=isDisabled>

then put the logic in a computed property…

computed: {
isDisabled() {
// evaluate whatever you need to determine disabled here…
return this.form.validated;
}
}

Solution 3:

Not difficult, check this.

<button @click=”disabled = !disabled”>Toggle Enable</button>
<input type=”text” id=”name” class=”form-control” name=”name” v-model=”form.name” :disabled=”disabled”>

jsfiddle

Solution 4:

the disabled attribute requires a boolean value:

<input :disabled=”validated” />

Notice how i’ve only checked if validated - This should work as 0 is falsey …e.g

0 is considered to be false in JS (like undefined or null)

1 is in fact considered to be true

To be extra careful try:
<input :disabled=”!!validated” />

This double negation turns the falsey or truthy value of 0 or 1 to false or true

don’t believe me? go into the console and type !!0 or !!1 :-)

Also, to make sure the number 1 or 0 are definitely coming through as a Number and not the String ‘1’ or ‘0’ pre-pend the value you are checking with a + e.g <input :disabled=”!!+validated”/> this turns a string of a number into a Number e.g

+1 = 1
+’1’ = 1

Like David Morrow said above you could put the conditional logic into a method - this gives you more readable code - just return out of the method the condition you wish to check.

Solution 5:

You can manipulate :disabled attribute in vue.js.

It will accept a boolean, if it’s true, then the input gets disabled, otherwise it will be enabled…

Something like structured like below in the case for example:

<input type=”text” id=”name” class=”form-control” name=”name” v-model=”form.name” :disabled=”validated ? false : true”>

Also read this below:

Conditionally Disabling Input Elements via JavaScript
Expression You can conditionally disable input elements inline
with a JavaScript expression. This compact approach provides a quick
way to apply simple conditional logic. For example, if you only needed
to check the length of the password, you may consider doing something
like this.

<h3>Change the Password</h3>
<div class=”form-group”>
<label for=”newPassword”>Please choose a new password</label>
<input type=”password” class=”form-control” id=”newPassword” placeholder=”Password” v-model=”newPassword”>
</div>

<div class=”form-group”>
<label for=”confirmPassword”>Please confirm the new password</label>
<input type=”password” class=”form-control” id=”confirmPassword” placeholder=”Password” v-model=”confirmPassword” v-bind:disabled=”newPassword.length === 0 ? true : false”>
</div>

Solution 6:

You may make a computed property and enable/disable any form type according to its value.

<template>
<button class=”btn btn-default” :disabled=”clickable”>Click me</button>
</template>
<script>
export default{
computed: {
clickable() {
// if something
return true;
}
}
}
</script>

Solution 7:

Can use this add condition.

<el-form-item :label=”Amount ($)” style=”width:100%” >
<template slot-scope=”scoped”>
<el-input-number v-model=”listQuery.refAmount” :disabled=”(rowData.status !== 1 ) === true” ></el-input-number>
</template>
</el-form-item>

[Vue.js] How to setup ASP.NET Core + Vue.Js?

I Need to integrate Vue.js to some ASP.NET Core MVC views. I picked Vue.js over other alternatives because it seemed to be simpler: -“just add it via <script> tag” they said. No need to learn gulp/grunt/webpack/browserify/etc.

That turned out to be false. At my first attempt to handle dates I tried some extensions like vue-moment or vue-datetime-picker, taken from this official curated list of awesome things related to Vue.js but I hit a wall here. While the first is not mandatory using the require() js syntax (CommonJS?), the second one doesn’t work without it. Other extensions happen to ‘use babel’ and imports/exports which is ECMAScript 6 that needs to be compiled. So, most vue.js libraries and toolings indeed needs a compiler, plus the require() syntax, and all that stuff from the node world?

How should I setup my project to work with ASP.NET Core MVC + Vue.js, in a way that I can develop many small vue-apps using vue.js plugins (that can require(stuff))?

Solution :

I was totally lost when I asked the above question. Ive spent a few days and I still dont have a complete picture. What when pretty sure is that 2016 is a hard year to learn JavaScript

I wanted to use Vue.JS because its simpler than the alternatives. Less ceremony, fewer boilerplates, less code. It’s branded as the Progressive Framework… Right! but only to a point. Vue.Js does not solve the Javascript ecosystem fragmentation problem with build systems.

So, you will have to pick a side: Do you need a javascript Modules and a build system?

Option 1: Keep it simple: Avoid Js modules and build systems.

Reasons to follow this path:

You dont have many days to learn A LOT of stuff. (configuring bundler, npm+package dependencies hell, ES6 stuff
You do not want to make a leading-edge Single-Page-Application. Embedding Vue.js inside a few HTML pages seems enough.
HTTP/2 is becoming mainstream, so bundlers like Webpack or Browserify will provide fewer benefits, at least on performance.
Eventually ES6 Modules will be supported directly in the browser, so we wont need to build whatever latest-javascript into browser-compatible-javascript.

You will save many days by not spending time learning stuff that will probably be obsolete in a few years.

If you follow this path, a few recommendations:

Just add js libraries using the <script> tag.
Only use browser-ready Javascript libraries. Whatever code that uses require() or the UMD prefix (function (root, factory) { requires you setup modules (therefore they are not browser ready unless you setup CommonJS). Js files with import/export statements are written in ES6 so avoid them too.
Use Bower to download browser-ready libs. Avoid NPM (which implies having a module system in place).

Caveat: You will not be able to use advanced Vue.js features like Single File Components or vue-router, but that is ok. You will have to do a few things manually.

Option 2: Learn Javascript Modules + build systems.

Prepare a few days to learn and not code. I will only explain briefly how Webpack worked for me. Browserify also works, but I haven’t tried it.

I recommend you spend some time learning what JavaScript Modules are. Then learn to build them and pack them: I used WebPack. Its documentation is not great, so what worked for me was to follow its tutorial step by step.

At this point, you may have heard that webpack ALSO has a builtin web-server with Hot-Module-Reloading. This is a web server for static files to be used only for development. Its benefit is that whenever you edit a JS module, the browser will automatically apply the change without refreshing. This is a very nice, but optional, feature. The problem: this built-in web-server competes with our web server (Kestrel). So, if you want to try this feature during development use the Webpack Asp.Net core Middleware provided at Microsofts JavaScriptServices repo . There you will find the WebApplicationBasic template that when currently using. I dissected it, removed most of its parts and by trying to use it I slowly understood what each part was originally for.

When using webpack you will mostly use 3 workflows:

Built-in development mode: Creates huge files, easy for debugging. Use it together with watch-mode so whenever you modify a file, a new Webpack build is triggered.
Build in production mode: Creates small minified files. Useful for dotnet publish.
Using Webpack-web-server+Hot-Module-Reload with Webpack Asp.Net core Middleware then the app will run Webpack in the background, build, and watch the source files for changes. The compilation output is not written to disk and only kept in memory and served via http. The JavaScriptServices middleware forwards requests from Kestrel to Webpack-web-server to make this work.

Whatever webpack config you go with, you have to include vue-loader into the webpack config. You may inspire in Vues webpack-simple template.

I havent covered everything that I wanted to, but this topic is too extensive and I need to go back to code. Please leave some feedback.

Solution 2:

I’m late to the party but now there is a template available for .Net Core that you can build with a single command. On a windows box with .Net Core installed just create an empty folder and in that folder run this command to show a list of available templates

dotnet new

If you don’t have all the templates you just need to run this to install the SPA templates:

dotnet new –install Microsoft.AspNetCore.SpaTemplates::*

And this to scaffold a new vue.js app:

dotnet new vue

In milliseconds a complete new Vue.js single page web app is built with a working .Net Core back end with controllers, views etc. It’s brilliant. Just open the project is VS or VS Code and you’re away.

There are also templates for Aurelia, Angular, Knockout and React! You can build them all and compare how each solves the same problem.
The Angular one even does server side pre-rendering out of the box!

I know .Net Core has a way to go but it’s becoming more and more awesome by the day!

Solution 3:

First, a disclaimer: I couldn’t find anything that really fit what I needed, so I put together a solution from scratch, see the end

You ask about including vue.js via the <script> tag (in that case the CDN build).
However, you also mention using Babel and the ES6 modules feature. In that case I would recommend using Webpack for the client side app, which will compile the ES6 with Babel, allow you to use modules and components, and work with a template! You also get hot module reload (edit the source and see changes in the client app in real time!) and Webpack will bundle the SPA into a static HTML5 app.

The official Vue.js docs point to their own Webpack template.

So you can run the Webpack dev server and the ASP.NET Core app independently, if that suits the needs, but there’s a better solution that makes development even more streamlined:

Microsoft’s open source JavaScriptServices lets you execute Node.js from ASP.NET Core, and they have some Webpack middleware that integrates the Webpack dev server into the app during debug builds.

They provide official templates for Angular 2, and even a template labeled Vue.js, but the vue.js template is just the official webpack template without any integration with .NET; this is just like the standalone server.

I couldn’t find any templates that did this for Vue.js, so I put together a sample ASP.NET Core application that loads the Webpack dev middleware with a Vue.js Webpack app. When the .NET Core server is running in dev mode, you can edit the vue.js source, and the changes will be reflected with quick incremental patches without needing to rebuild the entire application. In release mode, .NET Core will use the prebuilt Webpack output. You can find it on GitHub:

https://github.com/0xFireball/YetAnotherShrinker
The repository linked above has a full application demo that uses NancyFx, axios, Vue.js, and vue.js Material, and is a simple URL shortener. If you want steps for a more minimal setup that can easily be added to an existing app, check out this blog post of mine.

Obligatory disclosure: I wrote that blog post.

Solution 4:

You can try the steps below , or in case on this simple guide.

Setup the npm configuration file ( package.json )

Below is the npm package I will use.

{
“version”: “1.0.0”,
“name”: “asp.net”,
“private”: true,
“scripts”: {
“prod”: “gulp –production”,
“dev”: “gulp watch”
},
“devDependencies”: {
“gulp”: “^3.9.1”,
“laravel-elixir”: “^6.0.0-14”,
“laravel-elixir-vue-2”: “^0.2.0”,
“laravel-elixir-webpack-official”: “^1.0.2”,
“vue”: “^2.0.1”,
“vue-resource”: “^1.0.3”,
“vuex”: “^2.1.1”
}
}

Install the npm package

Open command prompt and go to the root folder of the application and
install the npm packages set from the package.json using the command
npm install without the quotes.

Setup Gulp

Once npm package is installed you may now setup the gulp file. You
will need to add new item called gulp configuration file ( gulpfile.js
). Later on we will create the vue.js js which we will call it vueApp.js
same with the code below. The first argument is where the public
output directory and the other one is the source directory for more
details on the webpack click here.

var elixir = require(‘laravel-elixir’);

require(‘laravel-elixir-vue-2’);

elixir(function (mix) {
mix.webpack(‘vueApp.js’, ‘wwwroot/js/dist’, ‘wwwroot/js’);
});

Create the vue.js js file

On the asp.net core web app project solution explorer goto wwwroot
and add js folder and if it does not exist then add again a new
folder name dist. Now once the folder setup is complete add a new
javascript file in the js folder name it vueApp.js.

Start coding in the vue.js js file

You may now start coding, as for the example below we will be display
alert to indicate that vue.js js is running.

import vue.js from ‘vue’

new Vue(
{
el: ‘#app’,
data() {
message:’hello world using vue.js js on Asp.net core mvc.’
},
mounted() {
console.log(this.message);
}
});

Apply vue.js js on to the razor view or html

Open the layout page and wrap the content of the body tag with a div
and an id of app. We will use app since that is the id tag we used
on our sample code from step 5. The app is not required and you may
change upon the desired name. Lastly on applying the vue.js js to file
add reference now to the script. Be sure to move outside the div app
the scripts reference to prevent error.

<body>

<div id=”app”>

<nav class=”navbar navbar-inverse navbar-fixed-top”>
<div class=”container”>
<div class=”navbar-header”>
<button type=”button” class=”navbar-toggle” data-toggle=”collapse” data-target=”.navbar-collapse”>
<span class=”sr-only”>Toggle navigation</span>
<span class=”icon-bar”></span>
<span class=”icon-bar”></span>
<span class=”icon-bar”></span>
</button>
<a asp-area=”” asp-controller=”Home” asp-action=”Index” class=”navbar-brand”>Project.Payrole</a>
</div>
<div class=”navbar-collapse collapse”>
<ul class=”nav navbar-nav”>
<li><a asp-area=”” asp-controller=”Home” asp-action=”Index”>Home</a></li>
<li><a asp-area=”” asp-controller=”Home” asp-action=”About”>About</a></li>
<li><a asp-area=”” asp-controller=”Home” asp-action=”Contact”>Contact</a></li>
</ul>
@await Html.PartialAsync(“_LoginPartial”)
</div>
</div>
</nav>
<div class=”container body-content”>
@RenderBody()
<hr />
<footer>
<p>© 2017 - Project.Payrole</p>
</footer>
</div>

</div>

<environment names=”Development”>
<script src=”~/lib/jquery/dist/jquery.js”></script>
<script src=”~/lib/bootstrap/dist/js/bootstrap.js”></script>
<script src=”~/js/site.js” asp-append-version=”true”></script>
</environment>

<environment names=”Staging,Production”>
<script src=”https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.2.0.min.js"
asp-fallback-src=”~/lib/jquery/dist/jquery.min.js”
asp-fallback-test=”window.jQuery”
crossorigin=”anonymous”
integrity=”sha384-K+ctZQ+LL8q6tP7I94W+qzQsfRV2a+AfHIi9k8z8l9ggpc8X+Ytst4yBo/hH+8Fk”>
</script>
<script src=”https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/bootstrap.min.js"
asp-fallback-src=”~/lib/bootstrap/dist/js/bootstrap.min.js”
asp-fallback-test=”window.jQuery && window.jQuery.fn && window.jQuery.fn.modal”
crossorigin=”anonymous”
integrity=”sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa”>
</script>
<script src=”~/js/site.min.js” asp-append-version=”true”></script>
</environment>

<script src=”~/js/dist/vueApp.js” asp-append-version=”true”></script>

@RenderSection(“Scripts”, required: false)
</body>

Run gulp

Now that we have set up the vue.js js configuration and apply it to our
razor view we will need to run gulp to to execute what we have set in
our gulpfile. Like in step 2 goto the root folder and open command
prompt then execute the command npm run dev again without the
quotes.

Run

Now for the final step run the asp.net core mvc app and check the
console of the web browser. You should be able to see now the message
we set from step 5.

(I wrote the guide on the blogpost for reference whenever I may need :D)

Solution 5:

Maybe someone will found this information helpful)

Here are some starter templates you can use for quick project setup.

The first one gives you multi-projects solution with some predefined architecture. This template more closely to real-world projects than the JavaScriptServices which was already mentioned here. It provides Domain layer, Repository layer and etc. Note that this is yeoman generator and it uses typescript.
https://github.com/vue-typed/generator-vue-net-core

The second just project on github and you should clone it if you want to use it. It is not a yeoman generator and I think this is regrettable, but I found structure in this template better than in the first one. Also, it has a lot of nice little things like some exception filters, that you, most likely, will still do anyway )). And if you are a beginner, this template will be for you just a godsend. This template recommended on the awesome-vue.js page. Here’s the link:
https://github.com/mrellipse/toucan

Solution 6:

I created this template that combines .NET MVC with Vue.js. You can use the entire vue.js ecosystem but if you don’t want it on any page you can just opt out.

GitHub: https://github.com/danijelh/aspnetcore-vue-typescript-template

Medium: https://medium.com/@danijelhdev/multi-page-net-core-with-vue-js-typescript-vuex-vue-router-bulma-sass-and-webpack-4-efc7de83fea4

You can use it as an example or starting point.

Solution 7:

I spent a long time learning how to use Browserify and Babel so I could setup my own ES6 environments. However, when it comes to using vue.js I’m quite happy to go with the default templates, which are best accessed by installing Vue-CLI. You can choose between Browserify and Webpack, and either simple setups or full on with linting, unit tests and Single File Components using the runtime-only version.

It just works.

Solution 8:

This question is a bit old but..

there is a little sample project in Github that uses aspx and vue.js , it uses yarn (or npm) as package manager and Webpack.

It is not .net core… but the way of using it will be the same… It might help you getting started.

The strange file structure is because it runs all on our Sitecore CMS system

Hope it helps.

[Vue.js] Activate router-link that has multi level nested routes with CRUD setup

I trying to setup deep nesting like below, and when kinda sure about we cannot use exact in router-link for nested routes.

<div id=”app”>
<nav class=”nav nav-main”>
<router-link exact to=”/“ class=”nav-link” activeClass=”active”>Dashboard</router-link>
<router-link to=”/projects” class=”nav-link” activeClass=”active”>Projects</router-link>
</nav>

<div class=”parent-content”>
<h4>Content for Parent goes here</h4>
</div>

<router-view>
<nav class=”nav nav-main”>
<router-link :to=”‘/projects/‘ + $route.params.projectId” class=”nav-link” activeClass=”active”>Deals</router-link>
<router-link :to=”‘/projects/‘ + $route.params.projectId + ‘/commitments/‘“ class=”nav-link” activeClass=”active”>Commitments</router-link>
</nav>
<router-view>
<div class=”child-content”>
<h4>Content for Child goes here</h4>
</div>
</router-view>
</router-view>
</div>

My Route:

routes: [
{
path: ‘/‘,
component: Dashboard
},
{
path: ‘/projects’,
component: Projects
},
{
path: ‘/projects/:id’,
name: ‘projects-detail’,
component: ProjectDetails,
children: [
// DEALS
{
path: ‘/projects/:projectId/deals’,
component: Deals
},
{
path: ‘/projects/:projectId/deals/:dealId/details’,
component: DealDetails
},
// COMMITMENTS
{
path: ‘/projects/:projectId/deals/:dealId/commitments/:commitmentId/edit’,
component: CommitmentEdit
}
]
}
]

With the above setup, I need to activate router-links, when the route is:
/projects/:projectId/deals/:dealId/details then activate Deals
/projects/:projectId/deals/:dealId/commitments/:commitmentId/edit then activate Commitments

Solution :

I think you have not another <router-view></router-view> inside ProjectDetails component add this and try.

Also remove /projects/:projectId from all child path as you have already in parent path path: ‘/projects/:id’,

So final you route would be

routes: [
{
path: ‘/‘,
component: Dashboard
},
{
path: ‘/projects’,
component: Projects
},
{
path: ‘/projects/:id’,
component: ProjectDetails,
children : [
// DEALS
{
path: ‘deals/:dealId/details’,//path will be /projects/:projectId/deals/:dealId/details
component: DealDetails
},
{
path: ‘deals’,.// path will be /projects/:projectId/deals
component: Deals
},
// COMMITMENTS
{
path: ‘/deals/:dealId/commitments/:commitmentId/edit/‘,
component: CommitmentEdit
}
]
}
]

Here is working fiddle : https://jsfiddle.net/chyLjpv0/16/

Read more about child path.

If you need not and component depended on parent dont make it as child use directly as root path like

routes: [
{
path: ‘/‘,
component: Dashboard
},
{
path: ‘/projects’,
component: Projects
},
{
path: ‘/projects/:id’,
component: ProjectDetails,
},
// DEALS
{
path: ‘/projects/:projectId/deals/:dealId/details’,
component: DealDetails
},
{
path: ‘/projects/:projectId/deals’,
component: Deals
},
// COMMITMENTS
{
path: ‘/projects/:projectId/deals/:dealId/commitments/:commitmentId/edit/‘,
component: CommitmentEdit
}
]

Working fiddle for this : https://jsfiddle.net/chyLjpv0/17/

Class router-link-exact-active is already working in this example : https://jsfiddle.net/chyLjpv0/18/ to display link as active

In the edit

Why you put <router-view> inside <router-view>. Outer is only working as it is being replaced and inner <router-view> is worthless. Use <router-view> in parent component for child component.

Also the inner <router-view> is not closed properly like </router-view>

[Vue.js] Vue.js get selected option on @change

First, to say that im new to Vue, and this is my first project ever using Vue.
there is combobox and to do something different based on the selected combobox. I use separate vue.html and typescript file.
Here’s my code.

<select name=”LeaveType” @change=”onChange()” class=”form-control”>
<option value=”1”>Annual Leave/ Off-Day</option>
<option value=”2”>On Demand Leave</option>
</select>

and here’s my ts file

onChange(value) {
console.log(value);
}

How to get selected option value in my typescript function? Thanks.

Solution :

Use v-model to bind the value of selected option’s value. Here is an example.

<select name=”LeaveType” @change=”onChange($event)” class=”form-control” v-model=”key”>
<option value=”1”>Annual Leave/ Off-Day</option>
<option value=”2”>On Demand Leave</option>
</select>
<script>
var vm = new Vue({
data: {
key: “”
},
methods: {
onChange(event) {
console.log(event.target.value)
}
}
}
</script>

More reference can been seen from here.

Solution 2:

@ is a shortcut option for v-on. Use @ only when you want to execute some vue.js methods. As you are not executing vue.js methods, instead you are calling javascript function, you need to use onchange attribute to call javascript function

<select name=”LeaveType” onchange=”onChange(this.value)” class=”form-control”>
<option value=”1”>Annual Leave/ Off-Day</option>
<option value=”2”>On Demand Leave</option>
</select>

function onChange(value) {
console.log(value);
}

If you want to call vue.js methods, do it like this-

<select name=”LeaveType” @change=”onChange($event)” class=”form-control”>
<option value=”1”>Annual Leave/ Off-Day</option>
<option value=”2”>On Demand Leave</option>
</select>

new Vue({


methods:{
onChange:function(event){
console.log(event.target.value);
}
}
})

You can use v-model data attribute on the select element to bind the value.

<select v-model=”selectedValue” name=”LeaveType” onchange=”onChange(this.value)” class=”form-control”>
<option value=”1”>Annual Leave/ Off-Day</option>
<option value=”2”>On Demand Leave</option>
</select>

new Vue({
data:{
selectedValue : 1, // First option will be selected by default
},


methods:{
onChange:function(event){
console.log(this.selectedValue);
}
}
})

Hope this Helps :-)

Solution 3:

The changed value will be in event.target.value

const app = new Vue({
el: “#app”,
data: function() {
return {
message: “Vue”
}
},
methods: {
onChange(event) {
console.log(event.target.value);
}
}
})
<script src=”https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
<div id=”app”>
<select name=”LeaveType” @change=”onChange” class=”form-control”>
<option value=”1”>Annual Leave/ Off-Day</option>
<option value=”2”>On Demand Leave</option>
</select>
</div>

[Vue.js] Proper way to re-initialize the data in VueJs 2.0

I was going through this answer on SO : Is there a proper way of resetting a component’s initial data in vuejs?

However, the current method is not allowed now and VueJS prohibits changing the $data var.

As you can see here in this https://github.com/vuejs/vue/issues/2873 ( $data is not allowed to be modified. )

So if I try the above method, when getting a VueJS warning:

[vue.js warn]: Avoid replacing instance root $data. Use nested data
properties instead.

Here is my JS code,

function initialState () {
return {
h2: 0,
ch4: 0,
c2h6: 0,
c2h4: 0,
c2h2: 0,
c3h8: 0,
c3h6: 0,
co: 0,
co2: 0,
o2: 0,
n2: 0,
selected: ‘’
}
}
export default {
name: ‘something’,
data () {
return initialState() // This is working fine
},
computed: {
tdcg: function () {
// some logic here…
}
},
methods: {
resetFields: function () {
this.$data = initialState() // –> This is what to achieve!
}
}
}

So what is the correct and the easiest way of re initialising my data?

Solution :

You can use Object.assign to iterate through all properties and assign them:

export default {
data () {
return {
h2: 0,
// other attributes…
};
},
methods: {
resetFields () {
Object.assign(this.$data, this.$options.data.call(this));
}
}
}

Here’s a demo fiddle: https://jsfiddle.net/797yyvtz/

Note: I’m using this.$options.data to call the original data method again to get a fresh copy of the data. No need for a separate initialState function. The data method is the initial state function.

Solution 2:

Did you try iterating through the initialState object and setting it again? Here is the sample code:

function initialState() {
return {
h2: 0,
ch4: 0,
// and so on… finally
selected: ‘’
}
}

export default {
name: ‘something’,
data: function() {
return initialState()
},
computed: {
// …
},
methods: {
resetFields: function() {
// Fetch the initialState object locally, so we do not have to call the function again
let initialData = initialState();
// Iterate through the props
for (let prop in initialData) {
// Reset the prop locally.
this[prop] = initialData[prop];
}
}
}
}

In my limited experiments locally, it does seem to work. Let me know the thoughts on this method.

Solution 3:

Wrap all the data into a dict with a key called “data” or other thing. Then you can re-initialize whole data by set this.data = {xx: yy}, or directly change one data item like this.data.h2 = 2.

function initialState () {
return {
h2: 0,
ch4: 0,
c2h6: 0,
c2h4: 0,
c2h2: 0,
c3h8: 0,
c3h6: 0,
co: 0,
co2: 0,
o2: 0,
n2: 0,
selected: ‘’
}
}
export default {
name: ‘something’,
data () {
return {data: initialState()} // This is working fine
},
computed: {
tdcg: function () {
// some logic here…
}
},
methods: {
resetFields: function () {
this.data = initialState() // –> This is what to achieve!
}
}
}

Solution 4:

You can try this:

Initialize the form data properties with required fields. (As seen in STEP 1)
Create another data field that will be used to clone the form data you want to reset (As seen in STEP 2).
Clone the form data required (STEP 3)
Write you reset method (STEP 4)
Use any where you prefer (STEP 5)

export default {
// Initialize the data
data() {
return {
// Initialize the form field (STEP 1)
formFields: {
name: ‘’,
email: ‘’,
password: ‘’,
moreData: {
field1: ‘’,
field2: [],
},
},
// Create an object property used for cloning (STEP 2)
formFieldsCopy: {},
};
},

// When the DOM is mounted copy the
// formField you want to a temporary field
// You can use lodash ._clone or ES6 spread operator (STEP 3)
mounted() {
this.formFieldsCopy = { …this.formFields
};
},
methods: {
// Write the function to reset the form (STEP 4)
resetFormFields() {
this.formFields = { …this.formFieldsCopy
};
},
submit() {
// Do you normal Axios requests here
// and call you reset function. (STEP 5).
this.resetFormFields();
},
},
};

Solution 5:

My solution:

mounted(){
this.saveData() // you can load if you need previous data
},
methods: {
saveData(){
localStorage.setItem(this.$options.name,JSON.stringify(this.$data));
},
loadData(){
if (localStorage.getItem(this.$options.name) !== null) {
let data= JSON.parse(localStorage.getItem(this.$options.name));
Object.keys(data).forEach((key)=>{this[key] = data[key];});
}
}
}

When you need you can load or save them again

[Vue.js] Vue.js change {{}} tags

to change the { something} by <% something %> in Vue.js, how could I achieve that, is it even possible?

An equivalent for what I look for in AngularJS:

var app = angular.module(‘app’, [], function($interpolateProvider) {
$interpolateProvider.startSymbol(‘<%’);
$interpolateProvider.endSymbol(‘%>’);
});

Thanks a lot for the help!

Solution :

You should modify the delimiters property of configuration object.

Vue.config.delimiters = [‘<%’, ‘%>’]

Edit: This solution works for vue.js 1.x and lower. See @Skip and @jaynabonne responses for vue.js 2.x solution

Solution 2:

With the latest version (2.0.5), the above doesn’t work. Rather than assigning to the global config, you pass the delimiters as an option to the vue.js instance:

new Vue({
el: ‘#app’,
data: data,
delimiters: [“<%”,”%>”]
});

At least, that’s what I had to do to make it work.

Solution 3:

when running vue.js 2.1.0 standalone and this is what I had to use

Vue.options.delimiters = [‘{[{‘, ‘}]}’];

[Vue.js] Implementing Vue.js + DataTables properly

Im trying to implement Vue.js + jQuery’s DataTables but there’s a weird things happening.

Check this fiddle on firefox (not working on chrome):
http://jsfiddle.net/chrislandeza/xgv8c01y/

when I change the state of DataTable (e.g. sort, search, etc.):

Newly added data on the list disappears
The DOM is not reading the directives or the vue.js properties

I’m pretty sure anyone who tried to mix vue.js+datatables experienced this problem. what did you do to solve this?

or is there a pure Vue.js script/plugin that has the same (or close) functionality like jquery’s DataTable? (pagination, searching, sorting, number of entries to show, etc.).

here’s the code from the fiddle above:

HTML:

<div class=’container-fluid’ id=”app”>
<div class=’row’>
<div class=’col-md-9’>
<table class=”table table-bordered” id=”app-datatable”>
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th></th>
</tr>
</thead>
<tbody>
<tr v-repeat=”user: users”>
<td>{ user.name }</td>
<td>{ user.age }</td>
<td>
<button type=”button” v-on=”click: foo(user)”>Action</button>
</td>
</tr>
</tbody>
</table>
</div>
<div class=’col-md-3’>
<div class=”form-group”>
<label>Name</label>
<input type=”text”
class=”form-control”
v-model=”newUser.name”
\>
</div>

<div class=”form-group”>
<label>Age</label>
<input type=”name”
class=”form-control”
v-model=”newUser.age”
\>
</div>
<button type=”submit” class=”btn btn-primary” v-on=”click: addUser()”>Add</button>
</div>
</div>
</div>

JavaScript:

$(document).ready(function () {
var dT = $(‘#app-datatable’).DataTable();
});

var vm = new Vue({
el: ‘#app’,
data: {
newUser: {},
users: [
{name: ‘Chris’, age: 1},
{name: ‘John’, age: 2}
]
},
methods:{
addUser: function(){
this.users.push(this.newUser);
this.newUser = {};
},
foo: function(user){
console.log(user.name);
}
}
});

any suggestions are greatly appreciated.

Solution :

To get the DataTables plugin integrated correctly with Vue, there are a few things to keep in mind:

Per the example, you can use var dT = $(‘#app-datatable’).DataTable(); to initialize the DataTables if you already have the data ready and rendered to the DOM. If you don’t have the DOM <table></table> fully rendered (perhaps due to data populated via a delayed ajax call), you can’t initialize the DataTables until the data is ready. As an example, if you have a fetchData method in the component, you can initialize the DataTable once the promise has been fulfilled.
To update the table once initialized, perhaps due to a change in the underlying table data, the best (perhaps the only way), is to first destroy the table, before the new data is received and written to the DOM by Vue:

var dT = $(‘#app-datatable’).DataTable();
dT.destroy();

Then, once the data (in the case, the users array) has been updated,
re-initialize the DataTable as so:

this.$nextTick(function() {
$(‘#app-datatable’).DataTable({
// DataTable options here…
});
})

The $nextTick is necessary to ensure vue.js has flushed the new data to the DOM, before re-initializing. If the DOM is updated after the DataTable plugin has been initialized, you’ll see the table data, but the usual sorting, paging, etc. won’t work.
Another important point, is to have a row id in the dataset, and set the key in the <tr></tr>:

<tr v-repeat=”user: users” track-by=”id”>

Without the track-by, vue.js will complain when flushing new data to the DOM after DataTables has been initializing, likely due to not finding DOM elements hi-jacked by DataTables.

Solution 2:

maybe you can use lifecycle hooks, infact these weird things are caused by competition of manipulating the DOM. in the vue.js instance, add a created() hook then initialize the DataTable, just like the following:

var vm = new Vue({
el: ‘#app’,
data: {
newUser: {},
users: [
{name: ‘Chris’, age: 1},
{name: ‘John’, age: 2}
]
},
methods:{
addUser: function(){
this.users.push(this.newUser);
this.newUser = {};
},
foo: function(user){
console.log(user.name);
}
},
created(){
this.$nextTick(function() {
$(‘#app-datatable’).DataTable();
})
}

});